运行PDO MySQL查询时出错,无法解决原因
如果我执行以下操作
$sql = 'SELECT * FROM ' . $table;
if ($where !== false)
$sql .= ' WHERE ' . implode(' AND ', $where);
$sql .= ' LIMIT 0, 1';
$variables = array('index');
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$statement = $this->DBH->prepare($sql);
$statement->execute($variables);
$statement->setFetchMode(PDO::FETCH_ASSOC);
$rows = $statement->fetch()
它工作正常,我得到了预期的结果。 但是如果我改变了
$sql .= ' LIMIT 0, 1';
$variables = array('index');
要
$sql .= ' LIMIT ?, ?';
$variables = array('index', 0, 1);
$ rows返回一个空数组,我发出以下警告;
Warning: PDOStatement::execute(): 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 ''0', '1'' at line 1 in file.php on line 96("$statement->execute($variables);"
输出的$ sql和$变量是:
SELECT * FROM ma_pages WHERE url = ? LIMIT ?, ?
Array ( [0] => index [1] => 0 [2] => 1 )
答案 0 :(得分:1)
试试这个:
$sql = 'SELECT * FROM ' . $table;
if ($where !== false)
$sql .= ' WHERE ' . implode(' AND ', $where);
$sql .= ' LIMIT :skip, :max';
$variables = array('index');
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$statement = $this->DBH->prepare($sql);
$statement->bindValue(':skip', 0, PDO::PARAM_INT);
$statement->bindValue(':max', 1, PDO::PARAM_INT);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
$rows = $statement->fetch()
答案 1 :(得分:0)
你必须像这样使用PDO::PARAM_INT
:
$sql .= " LIMIT :start, :end";
$statement->bindParam(':start', $start, PDO::PARAM_INT);
$statement->bindParam(':end', $end, PDO::PARAM_INT);