Search code examples
phptitle

Change title and description dynamically


I would like to generate a dynamic title and description from pages that require MySQL queries:

index.php

<html>
<head>
    <?php
    switch($page):
        case 'home':
            $body   = 'home.php';
            $title    = 'Home';  
        break;
    
        case 'contact':
            $body   = 'contact.php';
            $title    = 'Contact';  
        break;
    
        case 'members':
            $body   = 'members.php';
            $title    = 'I should put here the member profile';  
        break;
        
    /*
     * More pages
     */
        
        
    endswitch;

    ?>

    <title><?php echo $title; ?></title>
</head>

<body>
    <?php
        require_once $body;
    ?>
    
</body>

Then for instance I should call the pages, such as:

members.php page

<?php
$sql = "SELECT * FROM members WHERE mem_id = :mem_id";
/*
 * More codes
 */

foreach($res as $f):
    $mem_name       = $f['mem_name'];
endforeach;

$newTitle   = 'Profile of '.$meme_name;

 ?>

So how can I put the $newTitle generated from MySQL query inside the title tag

Thanks in advance


Solution

  • As we can see from the given code you can do below. If you dont really wanted to rewrite your whole code.

    members.php

    <?php
    $sql = "SELECT * FROM members WHERE mem_id = :mem_id";
    /*
     * More codes
     */
    
    foreach($res as $f):
        $mem_name       = $f['mem_name'];
    endforeach;
    
    $newTitle   = 'Profile of '.$meme_name;
    
    require_once $body;
     ?>
    
    // put this at the buttom of your body
    <script>
    document.title="<?php echo $newTitle;?>"
    </script>
    

    But it will be still recomended that you should prepare your server side variables at the beginning so you will not face that kind of issue.