Search code examples
phpsqlif-statementforeachecho

PHP - Both if and else conditions are executed on foreach loop


$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';              
    }
}

The result is the same on all pages:

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

The desired results:

  • When on home page : tag home
  • When on contact page: tag contact

Solution

  • Put a variable on the page that indicates which page it is. On the home page do:

    $current_page = "home";
    

    and on the contact page do:

    $current_page = "contact";
    

    Then you can just select the information for the page you're currently on:

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