Passing an array to a query using a WHERE clause

后端 未结 18 1060
情歌与酒
情歌与酒 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:34

    Col. Shrapnel's SafeMySQL library for PHP provides type-hinted placeholders in its parametrised queries, and includes a couple of convenient placeholders for working with arrays. The ?a placeholder expands out an array to a comma-separated list of escaped strings*.

    For example:

    $someArray = [1, 2, 5];
    $galleries = $db->getAll("SELECT * FROM galleries WHERE id IN (?a)", $someArray);
    

    * Note that since MySQL performs automatic type coercion, it doesn't matter that SafeMySQL will convert the ids above to strings - you'll still get the correct result.

提交回复
热议问题