【发布时间】:2011-03-16 15:51:19
【问题描述】:
我认为这可能是我的 pdo 获取数据方法的缺陷,
public function fetch_all($query, $params = array())
{
try
{
# prepare the query
$stmt = $this->connection->prepare($query);
# if $params is not an array, let's make it array with one value of former $params
if (!is_array($params)) $params = array($params);
# execute the query
$stmt->execute($params);
# return the result
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
# call the get_error function
$this->get_error($e);
}
}
所有传入这个方法的参数都会变成字符串,但是我需要整数用于sql LIMIT查询,比如下面
$sql = "
SELECT *
FROM root_pages
ORDER BY root_pages.pg_created DESC
LIMIT ?,?";
items = $connection->fetch_all($sql,array('0','6'));
返回这个错误,
2SQLSTATE[42000]:语法错误或 访问冲突:1064 你有一个 SQL 语法错误;检查 对应于您的 MySQL 的手册 正确语法的服务器版本 在第 32 行的 ''0','6'' 附近使用
我该如何解决?
编辑:
按照建议,我将方法中的代码更改为下面的代码,
# fetch a multiple rows of result as a nested array ( = multi-dimensional array)
public function fetch_all($query, $params = array())
{
try
{
# prepare the query
$stmt = $this->connection->prepare($query);
# if $params is not an array, let's make it array with one value of former $params
//if (!is_array($params)) $params = array($params);
foreach($params as $k=>$p){
if(is_numeric($p)){
$stmt->bindParam($k+1, $p, PDO::PARAM_INT);
}
else{
$stmt->bindParam($k+1, $p, PDO::PARAM_STR);
}
}
$stmt->execute();
# execute the query
//$stmt->execute($params);
# return the result
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
# call the get_error function
$this->get_error($e);
}
}
$items = $connection->fetch_all($sql,array(0,6));
然后我得到一个不同的错误,
2SQLSTATE[42000]:语法错误或 访问冲突:1064 你有一个 SQL 语法错误;检查 对应于您的 MySQL 的手册 正确语法的服务器版本 在第 32 行的 ''6'' 附近使用
编辑:
我刚改成,
if(is_int($p)){..}
但仍然出现相同的错误...叹息...
【问题讨论】:
-
你可能还需要
if (!is_array($params)) $params = array($params); -
@Rocket:你是对的!它现在正在工作!非常感谢。我可以问 - 为什么
$k+1?谢谢! -
它是
$k+1,因为 PHP 中的数组是零索引的,但bindParam希望第一个参数是1,而不是0(等等)。
标签: php string integer pdo prepared-statement