使用$ wpdb->为IN子句准备查询

时间:2018-06-07 07:05:05

标签: php mysql wordpress

// get_fav_fruit将水果名称作为字符串返回

$multipleFavFruits = get_fav_fruit( );

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

上述解决方案对我不起作用。

我已经为它创建了正确的解决方案,请看看答案。

1 个答案:

答案 0 :(得分:0)

// 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));