//get_fav_fruit 以字符串形式返回水果名称
$multipleFavFruits = get_fav_fruit( );
$color = $wpdb->get_var($wpdb->prepare(“SELECT color FROM $fruitsTable WHERE fruit IN (%s) , $multipleFavFruits));
上述解决方案对我不起作用。
我已经为其创建了正确的解决方案,请查看答案。
最佳答案
// 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));
关于php - 使用 $wpdb->prepare 查询 IN 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50734884/