我需要使用多个字符串查询数据库表。只有当;“标签”;列匹配所有字符串。我事先不知道字符串的数量(它是动态的)。
我想我很熟悉这段代码,但我没有从数据库中获得任何匹配项:
function getMatchingRecipes() {
// get the search query:
$tags = ($_POST["tagsToSearchWith"]);
// clean it up:
$tags = sanitize_text_field( $tags);
//explode to an array based on commas:
$explodedTagsArray = explode(\',\', $tags);
//construct query dynamically using the array
$myDynamicQuery = "SELECT * FROM recipesTable WHERE recipetags like %s";
$appendFormatIndicatorsWithLoop = ""; //empty the placeholder on every query
$i = 0; //for limiting the foreach loop to produce one less than the array has (because one like %s is already there by default)
foreach ($explodedTagsArray as $singleTag) {
$appendFormatIndicatorsWithLoop .= " AND recipetags like %s"; //do this as many times we have tags in the array
if(++$i > (count($explodedTagsArray)-2)) break;
}
$myDynamicQuery .= $appendFormatIndicatorsWithLoop; //appending
// ... do stuff with it
global $wpdb;
$recipe = $wpdb->get_results( $wpdb->prepare($myDynamicQuery, $explodedTagsArray), ARRAY_A ); //prepare now needs a minimum of two arguments. ARRAY_A is for get_results, and defines the return type to be an assosiative array
//log current status to console:
echo("<script>console.log(\'PHP: " . $myDynamicQuery . " array was: " . json_encode($explodedTagsArray) . "\');</script>");
echo json_encode($recipe);
};
这是控制台中整个查询和数组的外观:
<script>console.log(\'PHP: SELECT * FROM recipesTable WHERE recipetags like %s AND recipetags like %s array was: ["butter","bread"]\');</script>[]0
在我的数据库表中有一个名为recipetags的列。其中一行有;黄油、面包;在该列中。为什么我的查询与该行不匹配?是逗号放错了地方,还是我的格式不正确?