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 - Wordpress 子主题 style.css 已停止工作

html - 为 Contact 7 表单 Wordpress 添加边框和背景

php - 如何在 PHP 中计算视频长度和大小?

php - MySQL 更新 1 行表,之前的表正在更新

php - 更新和删除特定记录

php - 在 Wordpress 的 post 表中创建新字段还是创建新表更好

javascript - PHP AJAX jQuery 发送文件和文本

php - CakePHP,保存和访问逗号分隔的 MySQL 列以进行 "group"标识

mysql - 存储过程中非法混合排序规则 (utf8_general_ci,IMPLICIT) 和 (utf8_unicode_ci,IMPLICIT)