I currently have a table. If the user searches for something, I would like the query to return the filtered results. If the user doesn’t search for something, it should return all results. I’m not too sure how to do this with wpdb prepare.
if($search_query!=="all") {
$search_query = '%' . $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", $search_query,$current_page,$rows_per_page));
Right now nothing returns when the search field is empty because the query is erroring out because it’s throwing the parametrization off and passing $search_query to the %d beside LIMIT. Is it possible to make this variable conditional? Is there a way to do this without an IF statement ?
It looks like you can pass an array to
prepare
, as well as a list of variables, according to the WordPress documentationThat means that you could do something like this:
Your WHERE clause will be empty if there’s no data, so concatenating it into your query won’t cause issues.
Why not do the prepare in the “If” statement? You can then do the other prepare (without the where clause) in the “Else” and just use the get_results on the proper prepared query?
You can escape the
like
parameter yourself and add it as a where clause if needed like this:and remove the
search_query
param from theprepared
statement