How to use php array with sql IN operator?

后端 未结 13 1686
北恋
北恋 2020-11-29 06:23

I have and array with two values and I want to use it with sql IN operator in select query.

Here is the structure of my table

id comp_id
1   2
2   3
         


        
相关标签:
13条回答
  • 2020-11-29 06:44

    you need to convert the array into comma-separated string:

    $condition = implode(', ', $arr);
    

    And, additionally, you might want to escape the values first (if you are unsure about the input):

    $condition = implode(', ', array_map('mysql_real_escape_string', $arr));
    
    0 讨论(0)
  • 2020-11-29 06:47

    All the people here are proposing the same thing but i got a warning in WordPress because of a simple error. You need to add commas to your imploded string. To be precise something like this.

    $query = "SELECT *FROM table Where comp_id IN ( '" . implode( "', '", $sanitized_brands ) . "' )";
    

    Hoping it helps someone like me. :)

    0 讨论(0)
  • 2020-11-29 06:53

    You're mixing PHP and SQL - for the IN SQL operator, you need a format like:

    SELECT * from table WHERE comp_id IN (1,2)
    

    So to get that in PHP you need to do something like:

    $sql = "SELECT * from table Where comp_id IN (".implode(',',$arr).")"
    

    Bear in mind that this only works if the array comprises of integers. You have to escape each element if they are strings.

    0 讨论(0)
  • 2020-11-29 06:53

    You need something like:

    $sql = "SELECT * from table where comp_id in (".implode(',',$arr.")";
    
    0 讨论(0)
  • 2020-11-29 06:54

    you can only pass string to mysql as query, so try this

    mysql_query("SELECT * FROM table WHERE comp_id IN (".implode(',',$arr).")");
    
    0 讨论(0)
  • 2020-11-29 06:54

    If your array is of Integers :

    $searchStringVar = implode(",",$nameIntAryVar);
    $query="SELECT * from table NameTbl WHERE idCol='$idVar' AND comp_id IN ($searchStringVar)";
    

    If your array is of Strings :

    $searchStringVar = implode("','",$nameStringAryVar);
    $query="SELECT * from table NameTbl WHERE idCol='$idVar' AND comp_id IN ('$searchStringVar')";
    
    0 讨论(0)
提交回复
热议问题