2012-07-19 53 views
0

請幫忙:)。我gettig這個錯誤:這個PHP代碼調用mysqli ::準備SQL錯誤

Warning: mysqli::prepare() [mysqli.prepare]: (42000/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 '?(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id))' at line 1 in ***/classes/db.mysql.class.php on line 69 

Warning: mysqli::prepare() [mysqli.prepare]: (42000/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 ***/classes/db.mysql.class.php on line 75 

public function createTable($tableName) { 

    $this->connect(); 

    if ($stmt = $this->dbSocket->prepare("CREATE TABLE ?(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id))")) { 
     $stmt->bind_param("s", $tableName); 
     $stmt->execute(); 
     $stmt->close(); 
    } 

    if ($stmt = $this->dbSocket->prepare("INSERT INTO sys_userTables(userTableName) VALUES (u_?)")) { 
     $stmt->bind_param("s", $tableName); 
     $stmt->execute(); 
     $stmt->close(); 
    } 

    $this->disonnect(); 
} 

$ tablename是字符串,並正確地傳遞。

connect()方法是:

private function connect() { 
    $this->dbSocket = new mysqli($this->dbHost, $this->dbUser, $this->dbPassword, $this->dbDatabase); 
    if (mysqli_connect_errno()) { 
     printf("Brak połączenia z serwerem MySQL. Kod błędu: %s\n", mysqli_connect_error()); 
     exit(); 
    } 
} 

TIA。

+0

的【什麼是錯的SQL?](DUP HTTP:// stackoverflow.com/q/8215433/),[我可以在準備好的語句中參數化表名?](http://stackoverflow.com/q/11312737/) – outis 2012-07-19 10:50:59

+1

您不能綁定表名,只有參數。 – 2012-07-19 10:51:18

回答

2

不能使用表名作爲參數。

如果這點是創建具有相同的結構,但不同的名稱幾個表,我建議使用類似:

$table_names = array('a', 'b', 'c'); 

foreach($table_names as $name) { 
    $query = "CREATE TABLE `$name` (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id))"; 
    // run query or add it to a collection to run later 
    // or append a ';' to the end of the string and do it with a multi_query 
} 
+1

不要忘記轉義表名,因爲mysqli驅動程序不會轉義插入的變量。 – 2012-07-19 11:12:31

+0

我忽略了它!謝謝:) – 2012-07-19 11:15:28

+0

謝謝,這是問題。 – grasnal 2012-07-19 12:53:18