dongtuo3530 2014-02-11 23:44
浏览 21
已采纳

使用PHP中的PDO基于主键读取MySQL数据库

My code doesn't seem to work. I'm using the following:

$statement   = $db->prepare("SELECT * FROM carts WHERE (order_id = ':order_id')");
$result      = $statement->execute(array(':order_id' => $order_id));
$result      = $statement->fetch(); 

Which returns a boolean according to gettype($result); print_r($result) simply displays Array, though this is not expected. The data I'm reading is:

My Data

So I should expect an Array to be returned, not a Boolean. The PDO is correct and working, as I can call a write command. What's the best way using PDO to read a row based on the Primary Key order_id into a parsable array?

And as a split, is there a more efficient way than SELECT * WHERE to read a single row of data from a TABLE when the data is based on the Primary Key?

  • 写回答

2条回答 默认 最新

  • doumou8527 2014-02-12 00:06
    关注

    before all, set properly your error mode. If you can run the query with single quotes without an error popping, set this:

    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $statement = $db->prepare("SELECT * FROM carts WHERE order_id=:order_id");
    $result = $statement->execute(array(':order_id' => $order_id));
    $row = ($result ? $statement->fetch(PDO::FETCH_ASSOC) : array('problem' => 'with your query'));
    print_r($result);
    

    PDO fails with single-quotes around parameters. check your $result for the return value of execute(). you may have to specify a fetching mode for the fetch. depending on your sql database, parenthesis around the condition may also cause the query to fail.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等