SQL line is correct, but fetchAll is empty

I am deeply puzzled. I am trying to execute a SQL statement in my web application using php / PDO. Below 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 though I know there should be results in my result set. To debug, I cut and pasted my $ sqlString in MySQL Workbench and it always gives me the correct result set. So, I know that $ sqlString is legal.

Below is my $ sqlString:

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

      

+3


source to share


1 answer


You need to select the DB, i.e.: dbname=your_db

which is missing from your connection code.

For example:

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

      

According to the guide:



Also add:

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

      

right after opening a connection, as it checks for errors, a vital tool when coding.

Sidenote: Bug reports should only be done at the stage of staging and should never be done.

+6


source







All Articles