views:

197

answers:

2

How can you check an empty database result and then make an action based this?

My code which puts matching result to the if -clause

 while( $tags_and_Qid = pg_fetch_array( $result_tags )) {
      // Add the Tag to an array of tags for that question
      $end_array [ $tags_and_Qid['question_id'] ] ['tag'] [] = $tags_and_Qid['tag'];


  }

if ( $end_array [ $tags_and_Qid['question_id'] ] ['tag'] == '' ) {                                                                    
          // Problem here!                                                                       
    header( "Location: index.php?"
        . "no_question_found"
      ); 
  }
+1  A: 

You can use pg_num_rows(), e.g.

if (!pg_num_rows( $result_tags )) {
    // Problem here!                                                                       
    header( "Location: index.php?no_question_found");
    exit();
} 
while( $tags_and_Qid = pg_fetch_array( $result_tags )) {
      // Add the Tag to an array of tags for that question
      $end_array [ $tags_and_Qid['question_id'] ] ['tag'] [] = $tags_and_Qid['tag'];
}
Tom Haigh
+1  A: 
if(count($end_array) == 0)
{
    // No Results
}

I like to check the array I am using foreach on to check that it is a valid array rather than the database resource. This is because I might choose to filter some stuff out after grabbing the data, and if I check what the database returned, it isn't as accurate as checking the array I plan to be processing.

You could also do this as well.

if(pg_num_rows($result_tags) == 0)
{
    // Num Rows
}
Chacha102