根据标签搜索

时间:2017-07-22 18:07:48

标签: php

我有这两张桌子

        POSTS                         TAGS
[  id    -     title  ]        [ pid   -   tag ]
[  1     -  HelloWorld]        [ 1     -   PHP ]
[  2     -    Arrays  ]        [ 2     -   PHP]
[  3     -     AJAX   ]        [ 3     -   JQ  ]

和此搜索框

<form action="" method="post">
    <select name="tags">
        <option value="PHP">PHP</option>
        <option value="Echo">Echo</option>
        <option value="JQ">JQ</option>
    </select>
    <input type="submit" name="submit">
</form>

现在我的PHP代码

if(isset($_POST['submit']))
    $tag = $_POST['tags'];

    $query = "
    SELECT a.title FROM posts a
    INNER JOIN tags b ON a.id = b.pid
    WHERE b.tag = :tag
    ";

    $stmt = $pdo->prepare($query);
    $stmt->execute([':tag' => $tag]);
    while($row = $stmt->fetch()){
        $title = $row['title'];
        echo $title;
    }

但点击提交后没有任何反应,当我在html代码中选择id 1 & 2标记时,如何获得两个PHP标题?

1 个答案:

答案 0 :(得分:1)

你没有名为$ data的变量,而$ row:

$stmt->execute(['tag' => $tag]);
while($row = $stmt->fetch()){
        $title = $row['title'];
        echo $title;
}