我正在写一个类,编程创建一个给定某些列名称的表。我正在使用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