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

时间:2015-02-04 01:16:28

标签: php sql arrays pdo

我想从所选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));

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

1 个答案:

答案 0 :(得分:0)

由于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());