我在WHERE IN查询中苦苦挣扎

时间:2019-10-01 13:22:35

标签: php mysql database mysqli

我无法使用此代码。我已经回应了爆破(并且效果很好),但是我似乎无法使其与WHERE IN查询一起使用。

我尝试了echo导入,该导入有效,并且当我删除WHERE IN时,代码也可以正常工作,因此我知道'etc etc'中的元素也可以正常工作。

$filter_category = "SELECT * FROM `youcard_wp`.`bc_term_relationships`
WHERE term_taxonomy_id = '57'";
$result_c = $conn90->query($filter_category);
while($row_c = $result_c->fetch_assoc()){
    $category_filter[] = $row_c['object_id'];
}

echo implode(',', $category_filter); // <- works great

$get_offer_list = "
SELECT * FROM `youcard_wp`.`bc_posts`
WHERE `ID` IN ('".implode(',', $category_filter)."')
AND post_status = 'publish'
AND post_type = 'portfolio'
ORDER BY menu_order ASC
";
$result = $conn90->query($get_offer_list);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {

etc etc etc...

2 个答案:

答案 0 :(得分:1)

您不需要任何这些。而是使用这个...

SELECT x.columns
     , x.you
     , x.actually
     , x.want
  FROM bc_posts x
  JOIN bc_term_relationships y
    ON y.object_id = x.id
 WHERE x.post_status = 'publish'
   AND x.post_type = 'portfolio'
   AND y.term_taxonomy_id = 57
 ORDER 
    BY x.menu_order ASC

答案 1 :(得分:-2)

您将整个IN列表用一对单引号引起来,而您需要用引号将每个引号引起来。

考虑:

$get_offer_list = "
    SELECT * 
    FROM `youcard_wp`.`bc_posts`
    WHERE 
        `ID` IN ('" .implode("','", $category_filter)."')
        AND post_status = 'publish'
        AND post_type = 'portfolio'
    ORDER BY menu_order ASC
";

如果ID实际上是数字值而不是字符串,那么您根本不需要引号:

$get_offer_list = "
    SELECT * 
    FROM `youcard_wp`.`bc_posts`
    WHERE 
        `ID` IN (" .implode(",", $category_filter).")
        AND post_status = 'publish'
        AND post_type = 'portfolio'
    ORDER BY menu_order ASC
";