1

Possible Duplicate:
PHP/MYSQL using an array in WHERE clause

I have an array with ID values [1,5,2,6,7...] and I need to use that in a MySQL item_id IN (1,5,2,6,7...) statement to select only rows with an ID listed in the array. How can I go about converting the $arrIDs to something that I can insert into my SQL query?

EDIT- context of the call:

if(!IsNullOrEmptyString($_GET["view_playlist"])) {
        session_destroy();
    }
    $id_list = implode(",", $_SESSION("playlist"));
    $sql = 'SELECT t.track_id, t.track_title, t.track_num, al.album_title, g.genre_name, a.artist_name, t.length, t.track_rating '.
    'FROM track t, genre g, artist a, album al '.
    'WHERE t.track_id IN('.$id_list.' AND t.genre = g.genre_id AND t.artist = a.artist_id AND t.album = al.album_id';
Community
  • 1
  • 1
antonpug
  • 13,724
  • 28
  • 88
  • 129

2 Answers2

11

Use implode();

$ids = implode(',', $your_array);
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

If you're using PDO or mysqli (which you should, as the mysql_ functions are antiquated and should be abandoned), then you'll want to construct a parameterized query using the number of elements in your array to match the number of ?'s in your SQL.

Here's an example in PDO:

$ids = array(1, 2, 3, 4);

try {
    $dbh = new PDO("mysql:host=localhost;dbname=mydbname", 'username', 'password');
} catch(PDOException $e) {
    die($e->getMessage());
}

$inClause = trim(str_repeat('?, ', count($ids)), ', ');
$stm = $dbh->prepare('SELECT * FROM mytable WHERE id IN ('.$inClause.')');
$stm->execute($ids);

// resulting SQL: SELECT * FROM mytable WHERE id IN (?, ?, ?, ?)
webbiedave
  • 48,414
  • 8
  • 88
  • 101
  • I am using mysqli, and why do you think they are antiquated? They work great, never really had any issues? – antonpug Apr 30 '12 at 15:56
  • @antonpug: Did you really downvote me because **you** misread my answer? I never said not to use `mysqli` functions. I said the `mysql_` functions are antiquated and should be abandoned, not `mysqli`. This answer shows the proper way to do this using parameterized queries (which is the *preferred* way to use non-literal data in SQL). – webbiedave Apr 30 '12 at 16:00