构建具有多个赞的动态WPDB查询

时间:2021-01-13 作者:Andy Bay

我需要使用多个字符串查询数据库表。只有当;“标签”;列匹配所有字符串。我事先不知道字符串的数量(它是动态的)。

我想我很熟悉这段代码,但我没有从数据库中获得任何匹配项:

 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的列。其中一行有;黄油、面包;在该列中。为什么我的查询与该行不匹配?是逗号放错了地方,还是我的格式不正确?

1 个回复
SO网友:Andy Bay

让它工作起来,必须将类似的语句格式化如下:

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

相关推荐

Sort by price wpdb

我在wordpress上有一个页面可以搜索轮胎,一切都很好,但我想知道如何添加一个额外的列来按价格对它们进行排序。它们已经可以按大小和类型排序了。。。但我找不到价格的解决方案。提前感谢!代码如下: <?php $resultLargura = $wpdb->get_results ("SELECT wp_t.name FROM $wpdb->term_taxonomy AS wp_tt