我认为这可能是我的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)){..}
但仍然得到同样的错误......叹息......
答案 0 :(得分:7)
您应该使用PDO :: PARAM_INT类型传递参数,例如:
$sth->bindParam(':limit', $limit, PDO::PARAM_INT);
答案 1 :(得分:2)
<击>
尝试删除0
和6
周围的引号:
$connection->fetch_all($sql,array(0,6));
这应该是查询:
LIMIT 0,6
在0
和6
上加上引号,查询为:
LIMIT '0','6'
击> <击> 撞击>
编辑:在致电execute
之前致电bindParam
。
foreach($params as $k=>$p){
if(is_int($p)){
$stmt->bindParam($k+1, $p, PDO::PARAM_INT);
}
else{
$stmt->bindParam($k+1, $p, PDO::PARAM_STR);
}
}
$stmt->execute();
然后像这样致电fetch_all
:
$connection->fetch_all($sql,array(0,6));
答案 2 :(得分:2)
您无法通过占位符执行此操作。
PDO 总是引用非null
的参数,即使它们是整数。通常这不是一件坏事,但LIMIT
子句不能处理引用的整数。
你需要回归到老式的串联连接。因为您知道这些将是整数,所以您可以在连接之前通过调用intval
或casting来安全地处理它们。
$limit = intval($thing_that_provides_limit);
$offset = intval($thing_that_provides_offset);
$sql = "
SELECT *
FROM root_pages
ORDER BY root_pages.pg_created DESC
LIMIT {$offset}, {$limit}";
答案 3 :(得分:-2)
尝试:
$items = $connection->fetch_all($sql,array(0,6));
请注意0
和6
周围缺少引号 - 这会使PHP将它们视为整数,而不是您拥有的字符串。