2

例如,这很好用:

$dropTable = $dbConnection->prepare('DROP TABLE IF EXISTS announcements');
$dropTable->execute();

$createTable = $dbConnection->prepare('CREATE TABLE announcements(
            id MEDIUMINT NOT NULL AUTO_INCREMENT,
            announcements TEXT NOT NULL,
            PRIMARY KEY (id))');
$createTable->execute();

但这失败了:

$dropTable = $dbConnection->prepare('DROP TABLE IF EXISTS :tableToDrop');
$dropTable->bindParam(':tableToDrop', $_GET['table']);
$dropTable->execute();

$createTable = $dbConnection->prepare('CREATE TABLE announcements(
        id MEDIUMINT NOT NULL AUTO_INCREMENT,
            announcements TEXT NOT NULL,
            PRIMARY KEY (id))');
$createTable->execute();

有错误:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]:   
  Syntax error or access violation: 1064 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 '?' at line 1' in xxxx/createTables.php:9  
Stack trace: #0 xxxxx/createTables.php(9):   
  PDO->prepare('DROP TABLE IF E...') #1 {main} thrown in xxxx/createTables.php on line 9

我敢肯定这是微不足道的,但我已经做了好几个小时了。干杯。

编辑:原来你不能用表名绑定参数。无论如何用动态表名做一个安全的准备语句?

4

1 回答 1

1

Safe way (and u should use that, event if what u wrote could work):

$t=array('t1'=>'t1','t2'=>'t2'....'tn'=>'tn');

$sql = "drop table {$t[$_GET['table']]} ..."
于 2013-01-27T23:35:30.880 回答