2012-04-30 15:42
浏览 57

如何将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"])) {
    $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';

图片转代码服务由CSDN问答提供 功能建议

使用WHERE子句中的数组的PHP / MYSQL < / blockquote>

我有一个ID值为[1,5,2,6,7 ...]的数组,我需要在MySQL item_id IN中使用它(1,5 ,2,6,7 ...)语句只选择具有数组中列出的ID的行。 如何将$ arrID转换为可以插入SQL查询的内容?


 <  code> if(!IsNullOrEmptyString($ _ GET [“view_playlist”])){
 $ 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 2012-04-30 15:43

    Use implode();

    $ids = implode(',', $your_array);
    解决 无用
    打赏 举报
  • douman6245 2012-04-30 15:53

    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) {
    $inClause = trim(str_repeat('?, ', count($ids)), ', ');
    $stm = $dbh->prepare('SELECT * FROM mytable WHERE id IN ('.$inClause.')');
    // resulting SQL: SELECT * FROM mytable WHERE id IN (?, ?, ?, ?)
    解决 无用
    打赏 举报

相关推荐 更多相似问题