php - 使用 $wpdb->prepare 查询 IN 子句

标签 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));

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

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

最佳答案

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

相关文章:

php - PHP没有返回错误时调试MySQL插入失败

php - PHP 中的 CSS 压缩器

Java hibernate 使用 hibernate session 从 where 子句中的 OneToOne 关系获取实体

php - Doctrine 查询中的多个 ->select()

php - 我可以计算 session 以确定在线人数吗?

PHP `require_once` 包含错误的文件

mysql - 如何识别同一行内 3 个不同列中的重复数据并删除第二组重复数据?

javascript - 小部件中的 WordPress 核心颜色选择器(iris) - 在 WordPress 定制器中编辑时刷新

css - 如何在父菜单项而不是子菜单项下划线?

encryption - 有没有一个插件可以加密 WordPress 中存储的数据?