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

未捕获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
    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'");
    
    点赞 评论

相关推荐