doulu4413 2017-03-08 19:40
浏览 53
已采纳

PHP - MySQL语法错误(如何解决?)

I am trying to create tables based on a id that changes but i get a syntax error returned:

FAIL2: 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 '5 ( myID varchar(255), Data varchar(255), Related varchar(255), )' at line 1

@mysql_select_db('mydb'); // Connect to database

// Create Table
$tl = $myID[1];
$sqltable = $tl[0]; // Get first char from id

$sql = "CREATE TABLE IF NOT EXISTS $sqltable(myID varchar(255),Data varchar(255),Related varchar(255));";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
  die('FAIL2: ' . mysql_error());
}
echo "DONE<br>";

How can this be fixed?

  • 写回答

1条回答 默认 最新

  • dongwei2882 2017-03-08 21:06
    关注

    Try this, by way of example using mysqli_**

    $link = mysqli_connect('localhost', 'user', 'pass', 'test');
    /* check connection */ 
    if (!$link) {
      printf("Connect failed: %s
    ", mysqli_connect_error());
      exit();
    }
    $sqltable = 1234;
    $stmt = mysqli_prepare($link, "CREATE TABLE IF NOT EXISTS `{$sqltable}` (
            `myID` varchar(255),
            `Data_` varchar(255),
            `Related` varchar(255)
           );"
     );
    if (mysqli_stmt_execute($stmt)) {
        echo "success";
    } else {
       echo "failure";
    }
    mysqli_stmt_close($stmt);
    
    • In that case you cannot use a prepared statements in the table name, prepared statements only allow parameters to be bound to SQL statement , the table name is not one of those runtime values, as it determines the validity of the SQL statement itself and changing it at execution time would potentially alter the SQL statement that was valid.
    • Now,you should have a whitelist of table names that you check against first if the variable $sqltable is coming from user input in order to avoid sql injection.

    • Change the column 'Data', it is a reserverd word in MySQL

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划