Octavius
Octavius

Reputation: 583

Why am I getting "invalid argument being supplied for foreach"?

I am creating a search within my database and when I used the foreach construct for my results to be echoed I'm getting "invalid argument being supplied for foreach..". What I don't understand is why this error is coming up because the foreach containing my errors works fine.

if (empty($errors)){
    $results = search_results($keywords);
    $results_num = count($results);

    foreach ($results as $result){
        echo '<p> <strong>', $result['TITLE'], '</strong> </p>';
    }
} else {
    foreach($errors as $error){
        echo $error, '</br>';
    }
}

The part of the search_results function that's being focused on is this

$results = "SELECT TITLE FROM occupationalinfo WHERE $where"; 
$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results): 0;

if ($results_num === 0){
    return false;
}else{
    while ($results_row = mysql_fetch_assoc($results)) {
        $returned_results[] = array(
            'title' => $results_row['TITLE']
        );      
    }
}

I am still new to programming so I understand if there is something I may have missed or just not quite get. I would greatly appreciate any tips or constructive criticism.

Upvotes: 0

Views: 82

Answers (2)

RDK
RDK

Reputation: 4560

Try php function is_array().

if (empty($errors)){
           $results = search_results($keywords);
            if(is_array($results)){
               foreach ($results as $result){
                 echo '<p> <strong>'. $result['TITLE'] .'</strong></p>';
               }
            } else {
                echo "<p> <strong>empty</strong></p>";
            }
    } 

or

 if (empty($errors)){
        $results = search_results($keywords);
        if(is_array($results)){
             $results_num = count($results);
             foreach ($results as $result){
               echo '<p> <strong>'. $result['TITLE']. '</strong> </p>';
             }
        }        
    } else {
        foreach($errors as $error){
            echo $error, '</br>';
        }
    }

Upvotes: 0

Cat
Cat

Reputation: 67502

if ($results_num === 0){
    return false;
}

I'd bet this is executing, so it's returning false. You cannot apply foreach to false. Perhaps you should return array(), or just check for false:

$results = search_results($keywords);
if ($results !== false) {
    $results_num = count($results);

    foreach ($results as $result){
        echo '<p> <strong>',$result['TITLE'],'</strong> </p>';
    }
}

Upvotes: 5

Related Questions