douguabu8960
douguabu8960
2012-04-30 15:42

如何将PHP数组表示为逗号分隔的字符串? [重复]

已采纳

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';
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • down_load1117 down_load1117 9年前

    Use implode();

    $ids = implode(',', $your_array);
    
    点赞 评论 复制链接分享
  • douman6245 douman6245 9年前

    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 (?, ?, ?, ?)
    
    点赞 评论 复制链接分享