tags:

views:

327

answers:

2
+1  Q: 

PDO query problem

I am updating some code from the old mysql_* functions to PDO. It connects without a problem, runs the query without a problem, but the resultset is empty. PDO::query() is supposed to return a PDOStatement object, yet I am getting true in return. No errors are reported.

Here is my code:


try
{
    $DB = new PDO("mysql:host=localhost;dbname=dbname", "user", "pass");
    $stmt = $DB->prepare("SELECT * FROM report_clientinfo");
    $stmt->execute();
}catch(PDOException $e)
{
    echo $e->getMessage() . "\n";
}


echo gettype($stmt) . "\n";
if ($stmt) echo "true\n";
else echo "false\n";

$resultset = $stmt->fetchAll();

if(empty($resultset))
{
    exit("ERROR: getClientInfo query failed.");
}

$DB = null;

print_r($resultset);

The output I am seeing is:

object true ERROR: getClientInfo query failed.

Any ideas why it is not returning any results?

+4  A: 
object  
true  
ERROR: getClientInfo query failed.

It looks to me like your PDOStatement $stmt variable is in fact reported to be an object, not "true". The code then prints "true" when it sees that $stmt is non-null, which it is, because it's an object.

I recommend that you check the return value from $stmt->execute(). You might have an SQL error. For example, if you misspelled the table name, or the table doesn't exist in the database "dbname" that you connected to, or the user you login as doesn't have privilege to query that table.

Also check $stmt->errorInfo() to get more details on any error that occurred.

Bill Karwin
A: 

I'm a little embarrassed to report back that I was pointing to the wrong DSN. I guess that's what I get for trying to learn something new on just a few hours of sleep after going out for New Year's Eve. Thanks for the tip on the PDOStatement::errorInfo() method, I had not noticed it before.

Brian Griffin
No problem. On just a few hours sleep, it's hard to do anything well -- except sleeping!
Bill Karwin