使用 SQL 的 IN 从逗号分隔的字符串中获取数据库中的标签,转换为数组

Get tags from the database using SQL's IN from a comma separated string, converted to an array

我想从所选的身份证号码中获取数据,以获取带有这些标签的照片。这是我要使用的字符串:10,3,12。但就像现在一样,我收到以下错误消息:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''10,3' ORDER BY p.datetime_taken DESC' at line 7' in

这是我使用的代码:

$tags = explode(',', $_GET['tg']);
foreach($tags AS $tag) {
    $tag = $tag;
}

$in = implode(',', $tags);


# DATABAS (hämta)
$get_photos = sql("SELECT *
                   FROM photos AS p
                   JOIN tags_photos AS tp
                   ON tp.id_photo = p.id
                   JOIN tags_names AS tn
                   ON tp.id_tag = tn.id
                   WHERE tn.id IN :idtag
                   ORDER BY p.datetime_taken DESC
                  ", Array('idtag' => $in));


# FOTOGRAFIER
foreach($get_photos AS $photo) {
    echo $photo['data_file_name'];
}

$_GET['tg'] 包含 10,3,12.

如何修复此错误并从数据库中获取我需要的数据?

更新 代码现在看起来像这样:

$tags = str_replace(',', '?,', $_GET['tg']);

# DATABAS (hämta)
$get_photos = sql("SELECT *
                   FROM photos AS p
                   JOIN tags_photos AS tp
                   ON tp.id_photo = p.id
                   JOIN tags_names AS tn
                   ON tp.id_tag = tn.id
                   WHERE tn.id IN(:idtag)
                   ORDER BY p.datetime_taken DESC
                  ", Array('idtag' => $tags));

使用此代码,如果我在所选照片之前选择标签,照片将被替换。但是当我在选择的标签之后选择一个标签时,没有任何反应(加载部分除外)。

感谢 Atli,我(终于)开始工作了!这是解决方案:

$tags = $_GET['tg'];

# DATABAS (hämta)
$get_photos = sql("SELECT *
                   FROM photos AS p
                   JOIN tags_photos AS tp
                   ON tp.id_photo = p.id
                   JOIN tags_names AS tn
                   ON tp.id_tag = tn.id
                   WHERE tn.id IN(".$tags.")
                   ORDER BY p.datetime_taken DESC
                  ", Array());