mysql query search with “If” statement

So, I have following php query:

for($i = 0; $i < sizeof($cat_result) ; ++$i) {          
    $query_p    = "SELECT * FROM $table WHERE id = %d"; 
    $results[]  = $wpdb->get_row($wpdb->prepare($query_p, $cat_result[$i]));            
}   

The search relies on $cat_result which contains numerous numbers.

Read More

For example, let say $cat_result contains the following number: ‘1,3,5,21,35`

Using these 5 numbers, the query will look for the db info.

However, there are scenarios where some number (for example, “21”) do not exist in the db.

Then, I get PHP NOTICE: trying to get property of non-object.

How do I write “if” statement so that if the id (in this case “21”) does not exist, then it simply ignores the query? (It is hard to explain what I mean by “ignore”. I still want the query to do the search but if it does not find what it is looking for, then simply ignore the error).

Related posts

2 comments

  1. I think you should restructure your query. That way, as long as your data is sanitized (to prevent injection as im not sure if it comes from the user or not), you can just do the following:

    $cat_result = implode(",", $cat_result);
    $query_p    = "SELECT * FROM $table WHERE id in ( $cat_result )";
    $rslt       = $wpdb->get_results($query_p);
    // loop result
    

    That way, it will fetch you all in that list.

  2. Try this:

    for($i = 0; $i < sizeof($cat_result) ; ++$i) {          
        $query_p    = "SELECT * FROM $table WHERE id = %d"; 
        $row = $wpdb->get_row($wpdb->prepare($query_p, $cat_result[$i]));
        if ($row) {
            $results[]  = $row;
        }    
    }
    

    I don’t know WordPress, but I suspect get_row returns false when there are no more rows of results. Your code was putting false into $results when that happened, and later code was then trying to use that as an object.

Comments are closed.