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

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改