1

I've got the following code:

try { $db = new PDO('mysql:host=127.0.0.1;db=example', 'root', ''); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $db->query('SELECT * FROM posts'); } catch (PDOException $e) { echo $db->errorCode(); var_dump($db->errorInfo()); } 

And I get the following error:

3D000array(3) { [0]=> string(5) "3D000" [1]=> int(1046) [2]=> string(20) "No database selected" } 

However, this ONLY occurs when I include $stmt = $db->query('SELECT * FROM posts');

This is my first time with PDO, Would anyone know why this is not working? The database and table exist.

4
  • is database example exist? You should write database name at example Commented May 7, 2014 at 9:06
  • Try with localhost instead of 172.0.0.1 Commented May 7, 2014 at 9:06
  • should $stmt = $db->query('SELECT * FROM posts'); be something like $stmt = $db->prepare('SELECT * FROM posts'); Commented May 7, 2014 at 9:06
  • 2
    @Satya query and prepare are both valid Commented May 7, 2014 at 9:07

2 Answers 2

4

You have:

db=example 

You need:

dbname=example 

Sadly, there's no way to get an error message or notification of any kind if you mistype a DSN parameter.

Available parameters are documented at PDO_MYSQL DSN.

Sign up to request clarification or add additional context in comments.

Comments

0

dname and not only db

try { $db = new PDO('mysql:host=127.0.0.1;dbname=example', 'root', ''); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $db->query('SELECT * FROM posts'); } catch (PDOException $e) { echo $db->errorCode(); var_dump($db->errorInfo()); } 

http://www.php.net/manual/fr/book.pdo.php

Comments