0

I get an empty array when running:

try {
    $pdo = new PDO('mysql:127.0.0.1:dbname=mytodo', 'root', 'root');
}
catch (PDOException $e) {
    die('Could not connect.');
}

$statement = $pdo->prepare('select * from todos');

$statement->execute();

var_dump($statement->fetchAll());

I've checked the database and running the same query 'select * from todos' returns the results as expected. I've tried using different databases and tables. I always get an empty array. Any ideas as to what's going wrong? I'm running MAMP PRO and get the same issue whatever PHP version I choose.

Any answers or pointers greatly appreciated

StandardSpace
  • 400
  • 3
  • 8
  • 1
    do you need a semi colon instead of a colon after the loop back address? – john elemans Dec 22 '16 at 00:37
  • http://php.net/manual/en/pdo.connections.php `$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);` and you have `mysql:127.0.0.1:dbname` being a colon instead of a semi-colon, is that your real code or not? If so, checking for errors on that would have thrown you something about it. – Funk Forty Niner Dec 22 '16 at 00:42
  • @johnelemans they most certainly do, unless that was just a bad paste. – Funk Forty Niner Dec 22 '16 at 00:43

1 Answers1

2

By default PDO will die silently on a lot of query errors. Try to check for typo errors also.

How to view query error in PDO PHP

// The rest of the statement can also go into the try block. And why not echo the $e error msg if you have one?

Community
  • 1
  • 1
sasi
  • 322
  • 2
  • 9
  • Thanks, Late night coding typos. Updated code getMessage()); } $statement = $pdo->prepare('select * from todos'); $statement->execute(); var_dump($statement->fetchAll()); – StandardSpace Dec 23 '16 at 01:08
  • You can add multiple catch blocks. 1st catch '\Exception' then '\PDOException'. – sasi Dec 23 '16 at 08:06