Passing an array to a query using a WHERE clause

后端 未结 18 1026
情歌与酒
情歌与酒 2020-11-21 09:03

Given an array of ids $galleries = array(1,2,5) I want to have a SQL query that uses the values of the array in its WHERE clause like:



        
18条回答
  •  梦如初夏
    2020-11-21 09:49

    Because the original question relates to an array of numbers and I am using an array of strings I couldn't make the given examples work.

    I found that each string needed to be encapsulated in single quotes to work with the IN() function.

    Here is my solution

    foreach($status as $status_a) {
            $status_sql[] = '\''.$status_a.'\'';
        }
        $status = implode(',',$status_sql);
    
    $sql = mysql_query("SELECT * FROM table WHERE id IN ($status)");
    

    As you can see the first function wraps each array variable in single quotes (\') and then implodes the array.

    NOTE: $status does not have single quotes in the SQL statement.

    There is probably a nicer way to add the quotes but this works.

提交回复
热议问题