PHP-if和else条件都在foreach循环上执行

时间:2018-10-01 20:34:27

标签: php sql if-statement foreach echo

$stmt = $conn->query("SELECT DISTINCT(title) as title FROM table WHERE title IS NOT NULL")->fetchAll();
foreach ($stmt as $tag) {
    if ($tag['title'] == 'home'){
        print_r($tag);
        echo 'tag home';                
    } elseif ($tag['title'] == 'contact'){
        print_r($tag);
        echo 'tag contact';              
    }
}

所有页面上的结果都相同:

Array ( [title] => home [0] => home ) 
tag home
Array ( [title] => contact [0] => contact ) 
tag contact

所需结果:

  • home页上:tag home
  • contact页上:tag contact

2 个答案:

答案 0 :(得分:0)

看起来返回的$ stmt结果包含“ home”和“ contact”标题。

尝试一下:

$stmt = $conn->query("SELECT DISTINCT(title) as title FROM table WHERE title IS NOT NULL")->fetchAll();
foreach ($stmt as $tag) {
    var_dump($tag['title']);
}

您将对返回的数据有更好的了解。

答案 1 :(得分:0)

在页面上放置一个变量,以指示它是哪个页面。在主页上执行:

$current_page = "home";

并在联系页面上执行:

$current_page = "contact";

然后,您可以仅选择当前所在页面的信息:

$stmt = $conn->query("SELECT * FROM table WHERE title = '$current_page'")->fetchAll(PDO::FETCH_ASSOC);