我想用PHP和PDO創建一個MySQL表。我也希望參數化表名。我已經試圖實現這個,錯誤代碼如下所示。我可以使用PDO參數化語句創建MYSQL表嗎?
class databaseaccess {
public $hostname = 'localhost';
public $username = 'root';
public $password = 'root';
private $db = null;
public $rows;
public function __construct() {
try {
$this->db = new PDO("mysql:host=$hostname;dbname=noteshareproject", $this->username, $this->password);
}
catch (PDOException $Exception) {
throw new Exception("DB failed to connect ".$Exception->getMessage());
}
}
public function writetable($title,$id){
if ($this->db === null) throw new Exception("DB is not connected");
//query works with `:title` however keeps the commas. Gotta find out what is wrong.
$query = "CREATE TABLE noteshareproject.:title (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), username VARCHAR(20)) ENGINE=myISAM;";
$statement = $this->db->prepare($query);
$title = $title . $id;
$title = (string) $title;
$statement->bindValue(':title', $title, PDO::PARAM_STR);
$statement->execute();
print_r($statement->errorInfo());
echo $title;
}
}
上述代碼的輸出結果如下:
Array
(
[0] => 42000
[1] => 1064
[2] => 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 ''exampletablename'(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), username VARCHAR(20)) EN' at line >2
)
exampletablename
我做了什麼錯在我的MySQL語法或PDO實現?
您是否嘗試過手動查詢? –