0

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.

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43

1 Answers1

0

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'");
Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286