Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Using PHP with MySQL Querying the Database with PHP Working with Query Results

I have several problems with connection database shirts4mike over php

The first is already solved by adding a string 'USE shirts4mike;' to the quering string:

$results = $db->query(" USE shirts4mike; SELECT name, price FROM products ORDER BY sku asc" ); And quastion is: How to initialize this database in php and why in the code of Randy Hoyt it absent? The second, I have Exception error while using fetchAll() function:

<?php

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

try { $results = $db->query(" USE shirts4mike; SELECT name, price FROM products ORDER BY sku asc" ); echo "Our query ran successfully."; } catch (Exception $e) { echo "Data can not be retrieved from the database."; }

echo "<pre>"; var_dump($results -> fetchAll()); ?>

What is wrong with my code?

Output:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error' in C:\xampp\htdocs\database.php:26 Stack trace:

0 C:\xampp\htdocs\database.php(26): PDOStatement->fetchAll()

2 Answers

I think you're just missing host before localhost.

<?php

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

try {
  $results = $db->query(" USE shirts4mike; SELECT name, price FROM products ORDER BY sku asc" );
  echo "Our query ran successfully.";
} catch (Exception $e) {
  echo "Data can not be retrieved from the database.";
}

echo ""; var_dump($results -> fetchAll());

?>

Take a look here: https://teamtreehouse.com/forum/my-script-has-an-error

That's right, I've missed this one, haha. Thanks a lot.