doutale7115 2016-01-23 00: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 00: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'");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部