webrider
webrider

Reputation: 95

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.

Upvotes: 0

Views: 1963

Answers (2)

hair raisin
hair raisin

Reputation: 2628

My best guess would be that your first query is somehow being rerun with a blank value for $tablename

If this is a publicly accessible page, i'd be very careful about creating tables from user input. You also probably want to (at the very least) run $tablenale through mysql_real_escape_string() and change CREATE TABLE to CREATE TABLE IF NOT EXISTS

Upvotes: 1

bos
bos

Reputation: 6555

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 "(".

Upvotes: 0

Related Questions