尝试显示包含字符串的行时显示的所有行

时间:2014-10-12 06:47:48

标签: php sqlite

我有一些代码,我希望它只显示列中某个字符串的行。我有一个名为“标签”的列,其中有标签格式为“tag1,tag2”等。我希望有链接,以便人们只能显示带有特定标签的产品。这是我遇到问题的地方。我不能让它显示带有某些标签的行,它显示每一行。

<?php
try {
    //open the database
    $db  = new PDO('sqlite:prodDb.sqlite');
    $tag = $_POST['tag'];
    if (isset($tag)) {
        $result = $db->query('SELECT * FROM Products WHERE instr(Tags, $tag) > 0');
    } else {
        $result = $db->query('SELECT * FROM Products ');
    }

    //now output the data to a simple html table...
    $result = $db->query('SELECT * FROM Products');
    foreach ($result as $row) {
        print "" . $row['Id'] . "<br />";
        print "" . $row['Name'] . "<br />";
        $tags = explode(', ', $row['Tags']);
        foreach ($tags as $tag) {
            print "Tag: " . $tag . "<br />";
        }
        print "" . $row['Link'] . "<br />";
        print "" . $row['Screenshot'] . "<br />";
        print "" . $row['Download'] . "<br />";
    }


    // close the database connection
    $db = NULL;
}
catch (PDOException $e) {
    print 'Exception : ' . $e->getMessage();
}
?>

我出错的任何想法?

2 个答案:

答案 0 :(得分:1)

这可能不起作用,因为这里:

//now output the data to a simple html table...
$result = $db->query('SELECT * FROM Products');

您只是选择所有产品并忽略之前的查询/过滤器。

答案 1 :(得分:1)

在此处摆脱$db->query行:

//now output the data to a simple html table...
$result = $db->query('SELECT * FROM Products');

您将丢弃与该标记匹配的查询的结果,并使用此查询返回所有产品。

在带有标记的查询中,您有语法错误,因为您需要在字符串周围添加引号。最好使用准备好的查询:

$stmt = $db->prepare('SELECT * FROM Products WHERE INSTR(Tags, :tag)');
$stmt->execute(array(':tag' => $tag));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

此外,如果您在一列中包含所有标记,则表格设计较差。您应该通过将标记移动到单独的表中来标准化数据,每个产品的每个标记占一行。