doutale7115 2016-01-23 08:07
浏览 57
已采纳

未捕获PDOException:在PDOStatement对象上使用fetchAll()时SQLSTATE [HY000]

Hie, I am learning how to use PHP,and have followed everything in the tutorials I am watching to the letter but I don't understand why I am getting an error. Here is my code:

<?php

  try {
    $db = new PDO("mysql: host = localhost; dbname = tutorialdb", "root", "");
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf8'");
  } catch(Exception $e) {
    echo "Could not connect to database.";
    exit;
  }


  try {
    $results = $db->query("USE mydatab; SELECT name, price, img FROM products ORDER BY sku asc");
  } catch (Exception $e) {
    echo "Could not retrieve data.";
    exit;
  }

  echo "<pre>"
  var_dump($results->fetchAll(PDO::FETCH_ASSOC));

?>

Any positive input will be greatly appreciated, thank you.

  • 写回答

1条回答 默认 最新

  • ds122455 2016-01-23 08:45
    关注

    You should use query and exec for one SQL statement at a time:

    $db->exec("USE mydatab");
    $results = $db->query("SELECT name, price, img FROM products ORDER BY sku asc");
    

    It is possible to do otherwise, but there are some caveats. In general you could have multiple result sets, and you would need to indicate which of those you are retrieving. Life is a lot simpler if you just make separate calls.

    Side-note: you can specify the UTF-8 charset in the connection string, like this:

     $db = new PDO("mysql: host=localhost; dbname=tutorialdb; charset=UTF8",
                   "root", "");
    

    So then you don't need this:

     $db->exec("SET NAMES 'utf8'");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决