whistler
whistler

Reputation: 886

SQL String correct but fetchAll empty

I am thoroughly perplexed. I am trying to execute a SQL statement in my Web app using php/PDO. The following is my code:

$dbServer = DBSERVER;
$dbh = new \PDO('mysql:host=' . $myDBServer . ";port=3306", 'nameofserver', 'password', array(\PDO::ATTR_PERSISTENT => false));
$stmt = $dbh->prepare($sqlString);
$stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);

My results are ALWAYS an empty array, even when I know there should be results in my result set. To debug, I have cut and paste my $sqlString into MySQL Workbench and that always gives me the correct result set. So, I know that the $sqlString is legal.

The following is my $sqlString:

SELECT * FROM table1 t1 join table2 t2 ON t1.column1 = t2.column2 where t1.endDate is NULL AND t2.column3='2'

Upvotes: 3

Views: 117

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74216

You need to select a DB, i.e.: dbname=your_db which isn't present in your connection code.

For example:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

As per the manual:

Plus, add:

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

right after the connection is opened, since it will check for errors, a vital tool when coding.

Sidenote: Error reporting should only be done in staging, and never production.

Upvotes: 6

Related Questions