Quantcast
Channel: User andrewsi - Stack Overflow
Viewing all articles
Browse latest Browse all 51

Answer by andrewsi for Wordpress: wpdb prepare with conditional variable

$
0
0

It looks like you can pass an array to prepare, as well as a list of variables, according to the WordPress documentation

That means that you could do something like this:

$where = "";

$parameters = array($search_query,$current_page,$rows_per_page);

if($search_query!=="all") {
    array_push($parameters, '%' . $search_query . '%');
    $where = 'WHERE column_name LIKE %s';   
}

$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}table_name ".$where." ORDER BY id DESC LIMIT %d, %d", $parameters));

Your WHERE clause will be empty if there's no data, so concatenating it into your query won't cause issues.


Viewing all articles
Browse latest Browse all 51

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>