webrider webrider - 1 month ago 10
PHP Question

creating DB table by giving input from php text box

I want to make a table in a database, by giving the name of that table as an input from a text box.

<?php
$tablename = $_POST['tablename'];

// Create a MySQL table in the selected database
mysql_query("CREATE TABLE $tablename(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
firstpublish VARCHAR(255),
descriptions VARCHAR(255))") or die(mysql_error());
?>


it makes the table and the field, but i can't insert any data in it. When i run the code below

<?php
$firstpublish = $_POST['firstpublish'];
$descriptions = $_POST['descriptions'];

if(isset($_POST['firstpublish']) || ($_POST['descriptions']))
{
$order="INSERT INTO $tablename (id,firstpublish,descriptions) VALUES ('','$firstpublish','$descriptions')";
$result = mysql_query($order) or die (mysql_error());
}
?>


it showing an error message

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), firstpublish VARCHA' at line 1"
how can i fixed this problem.

-thankyou.

bos bos
Answer Source

The error is here:

mysql_query("CREATE TABLE $tablename(

Since you are mixing a variable in a quoted string, you insert whitespace after its name, because "$tablename(" is illegal name and will most likely be replaced will null, so the SQL-statement will actually be seen for MySQL as

CREATE TABLE id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), firstpublish VARCHAR(255), descriptions VARCHAR (255))

which, in turn, is a syntax error.

Solution: Add a space between $tablename and "(".