为什么我要从PHP PDO直接查询中获取数据,而不是在使用准备好的语句时获取错误?

为什么我要从PHP PDO直接查询中获取数据,而不是在使用准备好的语句时获取错误?,php,mysql,pdo,prepared-statement,Php,Mysql,Pdo,Prepared Statement,我尝试使用PHP的PDO模块运行一个非常基本的查询: SELECT product_id, product, unit_price FROM products WHERE type = *[some_user_selected_product_type]* 产品类型是数据库中的tinytext列,我通过HTTP POST请求数据 当我运行基本查询时,我得到的正是我所期望的 $type = 'widgets'; $result = $db->query("SELECT product_id

我尝试使用PHP的PDO模块运行一个非常基本的查询:

SELECT product_id, product, unit_price
FROM products
WHERE type = *[some_user_selected_product_type]*
产品类型是数据库中的tinytext列,我通过HTTP POST请求数据

当我运行基本查询时,我得到的正是我所期望的

$type = 'widgets';
$result = $db->query("SELECT product_id, product, unit_price FROM products WHERE type = '" . $type . "';";);
$result = $result->fetchAll(PDO::FETCH_OBJ);
echo json_encode($result);
生成我放入数据库的示例数据

[{产品编号:1004,产品编号:dingus,单价:22.00}, {产品编号:1005,产品编号:thingy,单价:10.00}]

但是,当我尝试使用一个准备好的语句来执行相同的查询时,当我尝试fetchAll时会出现一个错误,指出该操作不能在布尔值上执行

$type = 'widgets';
$query = $db->prepare("
            SELECT product_id, product, unit_price FROM products WHERE type = ?
            ");
$result = $query->execute([$type, ]);
// echo var_dump($result);
$result = $result->fetchAll(PDO::FETCH_OBJ);
echo json_encode($result);
产量

致命错误:在C:\xampp\htdocs\DM\db_utils.php的第125行调用成员函数fetchAll on boolean

我错过了什么?我读到的所有信息都表明,这些查询应该产生相同的结果。我甚至从数据库日志中提取查询,事实上,它们是相同的

3查询

SELECT product_id, product, unit_price
FROM products
WHERE type = 'widgets'
4查询

SELECT product_id, product, unit_price 
FROM products 
WHERE type = 'widgets'

尝试使用PDO::FETCH_ASSOC

$result = $result->fetchAll(PDO::FETCH_ASSOC);

尝试使用PDO::FETCH_ASSOC

$result = $result->fetchAll(PDO::FETCH_ASSOC);

您没有从数组[$type,]右删除绑定参数


您没有从数组[$type,]右删除绑定参数

试试这个

$type = 'widgets';
$query = $db->prepare("SELECT product_id, product, unit_price FROM products WHERE type =?");
$query->bindParam(1, $type, PDO::PARAM_STR);
$query->execute();
// echo var_dump($result);
$result = $query->fetchAll(PDO::FETCH_OBJ);
echo json_encode($result);
试试这个

$type = 'widgets';
$query = $db->prepare("SELECT product_id, product, unit_price FROM products WHERE type =?");
$query->bindParam(1, $type, PDO::PARAM_STR);
$query->execute();
// echo var_dump($result);
$result = $query->fetchAll(PDO::FETCH_OBJ);
echo json_encode($result);

您需要对准备好的查询对象调用fetchAll,而不是执行返回的布尔值

$query->execute();
$query->fetchAll();

您需要对准备好的查询对象调用fetchAll,而不是执行返回的布尔值

$query->execute();
$query->fetchAll();

如果说什么$结果{echo$result->errorInfo[2];}放在->execute-edit:$result,而不是$dbAs后面。erros说$result是布尔值,is应该是FALSE。因此,查询将失败。如果$结果{echo$result->errorInfo[2];}放在->execute-edit:$result,而不是$dbAs后面。erros说$result是布尔值,is应该是FALSE。因此,查询将失败。错误不会抱怨如何执行fetchAll$结果为布尔值false,因此查询失败错误不会抱怨如何执行fetchAll$结果为布尔值false,因此查询失败最后一项后的逗号为可选/不相关。最后一项是可选的/不相关的,请参见后面的逗号。见鬼!太简单了!我无法告诉你我在文档中对此隐瞒了多少次!非常感谢。天哪!太简单了!我无法告诉你我在文档中对此隐瞒了多少次!非常感谢。