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 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示