Syntax for $wpdb->prepare when searching in two columns
문제
I have this working statement for searching a single column in my database:
$foods = $wpdb->get_results( $wpdb->prepare( "SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %s", "%$search_text%"), ARRAY_A );
I would like to include another column in the search called "foodname" but I can't seem to figure out the correct syntax.
How should I formulate my prepare statement so that I'm searching "namevariations" OR "foodname" and a match in either column will select that row?
해결책
The part after WHERE
decides which columns are searched.
So you need to change it this way:
$foods = $wpdb->get_results(
$wpdb->prepare(
"SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %1$s OR foodname like %1$s",
'%' . $wpdb->esc_like( $search_text ) . '%'
),
ARRAY_A
);
Also you were using LIKE queries incorrectly. If the $search_text
contained %
character, it would be interpreted as wildcard and not as simple character. That's why I've added some escaping in your code. More on this topic here: How do you properly prepare a %LIKE% SQL statement?
다른 팁
Got it to work like this:
$recipes = $wpdb->get_results($wpdb->prepare("SELECT * FROM recipestable WHERE ( recipetags LIKE '%%%s%%' or recipename LIKE '%%%s%%' )", $like, $like ), ARRAY_A )