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


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

我想从选定的ID号中获取数据,以获取带有这些标签的照片。这是我要使用的字符串: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());