当我将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
));
结果:
来自PDO db类的SQLSTATE [HY093]:参数号无效:绑定变量数 与令牌数量不匹配
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);
}
}
答案 0 :(得分:0)
您要做的事情(将null
作为参数传递给execute
)是不可能的。正如documentation所述:
input_parameters
具有与绑定参数一样多的元素的值数组 在正在执行的SQL语句中。 所有值都被视为 PDO :: PARAM_STR 强>
如果要传递null
,则必须使用
$stmt->bindValue(1, null, PDO::PARAM_NULL);
或使用命名参数的等效语法。