使用$wpdb->prepare query for in子句

i2byvkas  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(263)

//get\u fav\u fruit以字符串形式返回水果名称

$multipleFavFruits = get_fav_fruit( );

$color = $wpdb->get_var($wpdb->prepare(“SELECT color FROM $fruitsTable WHERE fruit IN (%s) , $multipleFavFruits));

上述解决方案对我不起作用。
我已经为它创造了正确的解决方案,请看看答案。

ryevplcw

ryevplcw1#

// Count the number of fruit names

$favFruitsCount = count($multipleFavFruits);

// Prepare the right amount of placeholders, in an array

 // For strings, you would use, ‘%s’

$stringPlaceholders = array_fill(0, $favFruitsCount, ‘%s’);

// Put all the placeholders in one string ‘%s, %s, %s, %s, %s,…’

$placeholdersForFavFruits = implode(‘, ‘, $stringPlaceholders);

Now, our query with multiple placeholders would be:

$query = “SELECT color FROM $fruitsTable WHERE fruit IN $placeholdersForFavFruits”;

// get the corresponding colors for the fruits

$mutlipleColors = $wpdb->get_results($wpdb->prepare($query, $multipleFavFruits));

相关问题