简体   繁体   English

MySQL PHP, SELECT 条件是数组

[英]MySQL PHP, SELECT WHERE condition is an array

I am trying to SELECT products from db WHERE condition is an array.我正在尝试从 db WHERE 条件为数组的 SELECT 产品。 My method is working when array is declared but not when elements of array are generate after submitting form.我的方法在声明数组时有效,但在提交表单后生成数组元素时无效。

    $selected_categories = array();        //create empty array

    if(isset($_POST['submit'])){          //if form is submitted

        $name = $_POST['category'];

        foreach ($name as $category){
            $selected_categories[] = $category;          //add all checked checkboxes values into the array, every single $category element is text i.e. programming science
        }


        $get_products = "SELECT P.*, C.category_name, GROUP_CONCAT(category_name SEPARATOR ', ') AS cat FROM products P NATURAL JOIN categories C NATURAL JOIN product_to_categories WHERE category_name IN ('$selected_categories') GROUP BY product_name ORDER BY 1 DESC LIMIT $start_from,$per_page";
    }

the problem (i think) is in array, because when I am using one element from the array:问题(我认为)在数组中,因为当我使用数组中的一个元素时:

... WHERE category_name IN ('$selected_categories[1]')...

is working correctly it is also working when using:工作正常它在使用时也可以工作:

... WHERE category_name IN ('programming', 'science')...

WHERE category_name IN ('$selected_categories') is wrong - the parameter will be treated as ONE string literal, not as a list of separate literals. WHERE category_name IN ('$selected_categories')错误 - 参数将被视为 ONE 字符串文字,而不是单独文字的列表。

Use WHERE FIND_IN_SET(category_name, '$selected_categories') .使用WHERE FIND_IN_SET(category_name, '$selected_categories')

Separate values in $selected_categories must be separated by comma strictly (if some another separator is used then replace it). $selected_categories中的单独值必须用逗号严格分隔(如果使用了其他分隔符,则替换它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM