【发布时间】:2011-09-20 20:41:24
【问题描述】:
当我在下面的查询中使用 PHP PDO fetchOject 时,这似乎是一个错误或问题,
查询:
SELECT
p.*,
t.*
FROM root_pages AS p
LEFT JOIN root_templates AS t
ON p.tmp_id = t.tmp_id
WHERE p.pg_url = ?
AND ? IS NOT NULL
OR p.pg_url = ?
AND p.pg_hide != ?
从 PHP PDO db 类调用,
$page = $this->database->fetch_object($sql,array(
$pg_url,
NULL,
$pg_url,
1
));
结果:
SQLSTATE[HY093]:无效的参数号:绑定变量的数量 令牌数不匹配
来自 PDO db 类的 PHP PDO FetchOject 方法,
# return the current row of a result set as an object
public function fetch_object($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->fetchObject();
//return $stmt->fetch(PDO::FETCH_OBJ);
}
catch (PDOException $e)
{
# call the get_error function
$this->get_error($e);
}
}
只要我这样调用方法就好了,
$page = $this->database->fetch_object($sql,array(
$pg_url,
1,
$pg_url,
1
));
但是当我使用phpMyAdmin 测试以下查询之一时,我可以得到没有任何错误的结果,
SELECT
p.*,
t.*
FROM root_pages AS p
LEFT JOIN root_templates AS t
ON p.tmp_id = t.tmp_id
WHERE p.pg_url = 'exhibition sample 6'
AND '1' IS NOT NULL
OR p.pg_url = 'exhibition sample 6'
AND p.pg_hide != '1'
或
SELECT
p.*,
t.*
FROM root_pages AS p
LEFT JOIN root_templates AS t
ON p.tmp_id = t.tmp_id
WHERE p.pg_url = 'exhibition sample 6'
AND NULL IS NOT NULL
OR p.pg_url = 'exhibition sample 6'
AND p.pg_hide != '1'
我在使用fetchOject 时遗漏了什么想法?
编辑:
$sql ="
SELECT
p.*,
t.*
FROM root_pages AS p
LEFT JOIN root_templates AS t
ON p.tmp_id = t.tmp_id
WHERE p.pg_url = 'exhibition sample 6'
AND ? IS NOT NULL
OR p.pg_url = 'exhibition sample 6'
AND p.pg_hide != '1'
";
没有错误
$item = $connection->fetch_assoc($sql,1);
或
$item = $connection->fetch_assoc($sql,NULL);
fetch_assoc 方法,
# fetch a single row of result as an array ( = one dimensional array)
public function fetch_assoc($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->fetch();
}
catch (PDOException $e)
{
# call the get_error function
$this->get_error($e);
}
}
【问题讨论】: