MySQL Php Syntax Error, Check the manual

I have been having trouble with my code, and I keep getting this error. 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 '[table_name]" at line 1

My code for this is as follows:

 <?
//indicate the database you want
$db_name="test";

//connect to database
$connection = @mysql_connect("localhost","root","") or die (mysql_error());
$db = @mysql_select_db($db_name,$connection) or die (mysql_error());
//start the sql statement
$sql = @"CREATE TABLE $_POST[table_name] (";


for ($i =0;$i < count($_POST['field_name']);$i++){
    $sql .=$_POST['field_name'][$i]." ".$_POST['field_type'][$i];
    if ($_POST["field_length"][$i] !="") {
        $sql .= " (".$_POST ["field_length"][$i]."),";
    } else {
        $sql .= ",";
    }
}
//clean up
$sql = substr($sql,0,-1);
$sql .= ")";
//execute
$result = mysql_query($sql,$connection) or die(mysql_error());

//get a good message for success
if ($result) {
    $msg = "<P>".$_POST['table_name']." has been created!</p>";
    }
    ?>

I have a form seperate for table name, and number of fields, a seperate php doc for the other database stuff, it is just giving me trouble on my local host whenever I try to run this document after the other two.

After Echoing edited statements for $sql and $_POST I received the message,

"CREATE TABLE $_POST[table_name]"...$_POST[table_name]"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 '[table_name]"...hey char (1))' at line 1"


看起来像$_POST[table_name]不会替换您的查询尝试中的值

$sql = "CREATE TABLE ". $_POST['table_name']." (";

You have to put table_name in ', because you want to access the $_POST['table_name'].

That's why your query must begin like this:

"CREATE TABLE ".$_POST['table_name']."..

And you should always escape $_POST[] or $_GET[] values to prevent SQL Injection.

Use the function mysql_real_escape_string($_POST...) for escaping or use prepared statements with PDO.

Also mysql_... is deprecated. Switch to mysqli_..!

链接地址: http://www.djcxy.com/p/69764.html

上一篇: Dalvik正在寻找扩展名为“.0”的.so文件

下一篇: MySQL Php语法错误,查看手册