1

I'm trying to run this simple query:

try {
    $dsn = "mysql:host=localhost;dbname:mydb";
    $PDO = new PDO($dsn, 'root', '');
    $statement = $PDO->query("SELECT * FROM posts");
    var_dump($statement);  
} catch (PDOException $e) { exit($e->getMessage()); }

and this output:

bool(false) 

I'm really getting mad about this error. I tried to run the query on my database. $PDO is a PDO Object so technically it is connected to the database. It also seem that nothing gets wrong in all the pro functions. Running the copied and pasted query from $PDO->query() on phpmyadmin return a list of 2 record. I don't know what to do seriously. I'm starting to pull my hair and hit the wall with the head (it's not a metaphor). What am I doing wrong?

Shoe
  • 74,840
  • 36
  • 166
  • 272

2 Answers2

5

You have a DSN problem.

dbname:mydb

should be

dbname=mydb

Don't you just love programming?


In addition to the above statement, you should nevertheless enable Exceptions in your PDO attributes. It's done by adding the following statement right after the connection:

$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Further Points

  • Naming Convention - It's an accepted naming convention that variable names begin with a lower case letter, and every consecutive word is in Camel Case, or using underscores.
    Examples: $pdo, $databaseConnection $awesomeMultipleWordedVariable, $another_awesome_multiple_worded_variable.
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
1

You should enable PDO Exceptions:

$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
middus
  • 9,103
  • 1
  • 31
  • 33