我正在寫一個類,編程創建一個給定某些列名稱的表。我正在使用PDO準備好的語句,這似乎會導致一些問題。PHP的PDO問題與bindValue()
下面是基本過程:
// create a query string to be sent to $pdo->prepare
$sql =
'CREATE TEMP TABLE :tmp_table_name (
:person_id bigint,
:encntr_id bigint,
:prsnl_id bigint,
:program_detail text,
:program_name text
);';
$stmt = $pdo->prepare($sql);
// Bind table name
$stmt->bindValue(':tmp_table_name', 'tmp_patients', PDO::PARAM_STR);
// Bind column names
$columnNames = [
'person_id',
'encnt_id',
'prsnl_id',
'program_detail',
'program_name',
];
foreach($columnNames as $name) {
$stmt->bindValue(':'.$name, $name, PDO::PARAM_STR);
}
$ret = $stmt->execute();
// $ret is false! The statement fails.
這裏是$stmt->errorInfo()[2]
顯示:
ERROR: syntax error at or near "$1"
LINE 1: CREATE TEMP TABLE $1 ($2 bigint,
$3 bigint,
$4 bigint,
$5 text,
$6 te...
爲什麼$ 1,$ 2,$ 3等顯示在查詢呢?你有關於如何進一步調試這個PDO陳述的提示嗎?
更新 我嘗試了不同的方法,不使用bindParam,只是路過的則params的數組$ stmt->的execute()。我仍然得到同樣的錯誤,但...
$stmt = $this->pdo->prepare($this->createSql);
$keys = [];
// Bind column names
foreach($this->columnNames as $name) {
$keys[] = ':'.$name;
}
$params = array_combine($keys, $this->columnNames);
// Bind table name
$params[':tmp_table_name'] = 'tmp_'.$this->objName;
$ret = $stmt->execute($params);
if (!$ret) {
throw new Exception('execSchema() failed! '. $stmt->errorInfo()[2]);
}
爲什麼bindValue代替bindParam? http://www.php.net/manual/es/pdostatement.bindparam.php – fiunchinho 2012-08-02 19:40:58
@ONe因爲bindValue更靈活(我可以使用字符串作爲bindValue的值,bindParam需要該值是一個變量。)http:///stackoverflow.com/questions/1179874/pdo-bindparam-versus-bindvalue – nnyby 2012-08-02 19:43:35
請記住,您也可以發送參數來執行($ params)http://www.php.net/manual/es/pdostatement.execute.php – fiunchinho 2012-08-02 20:04:41