MeltingDog
MeltingDog

Reputation: 15458

ModX PDO SQL returns empty array

I pretty much copy/pasted this from the ModX RTFM:

$results = $modx->query("SELECT * FROM `saved_jobs` WHERE `job_id` = $job_id AND `user_id` = $user");

if (!is_object($results)) {
   return 'No result!';
}
else {

    $r = $results->fetchAll(PDO::FETCH_ASSOC);
    echo $r;
    echo "<br>count " . count($r);
    print_r($r);

}

But even though there are no records in the database I still get the 'else' occurring. The line echo "count " . count($r); produces the output: count 0

Does anyone know whats going on and how to fix it?

Upvotes: 0

Views: 213

Answers (1)

Sean Kimball
Sean Kimball

Reputation: 4494

If your query is successful, you still create an object with your first statement.

take a peek [also from the docs]:

$result = $modx->query("SELECT * FROM modx_users WHERE id='blah'");

echo '<pre>'; var_dump($result); echo '</pre>';

if (!is_object($result)) {
   return 'No result!';
}
else {
   $row = $result->fetch(PDO::FETCH_ASSOC);
   return 'Result:' .print_r($row,true);
}

What you want to do is find out if the object actually contains a result set:

$result = $modx->query("SELECT * FROM modx_users WHERE id='1'");

echo '<pre>'; var_dump($result); echo '</pre>';

if (!is_object($result)) {
  return FALSE;
}

if(sizeof($result) > 0){

  while($row = $result->fetch(PDO::FETCH_ASSOC)){
    echo'Result:' .print_r($row,true);
  }

}

so you can either test the size of the $result variable or just run the while loop & test if it has any data as well.

Upvotes: 1

Related Questions