如何将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';
可能重复: strong>
使用WHERE子句中的数组的PHP / MYSQL p>我有一个ID值为[1,5,2,6,7 ...]的数组,我需要在MySQL item_id IN中使用它(1,5 ,2,6,7 ...)语句只选择具有数组中列出的ID的行。 如何将$ arrID转换为可以插入SQL查询的内容? p>
调用的EDIT-上下文: p>
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'; code> pre> div>
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 (?, ?, ?, ?)