views:

114

answers:

5

I've been using headers to create templates for websites. It's easy, and very convenient for debugging.

I now face the problem of using head BUT with custom page titles. If this is my header.php >

<html>
    <head>
        <title> My Site : ??? </html>
    </head>
<body>


</body>
</html>

I need ??? to be replaced for every page.

Is this possible? If so, how? Thank you. : )

A: 

you could query a DB for the title of a page and then print it using php :)

Edit:

Looking back at the problem , depending on how you have your website designed this may not be the simplest solution. But if you are already using some sort of ID system this should be easy.

Ravi Vyas
+2  A: 

Not knowing more about your file inclusion scheme, the simplest way would be:

page2.php

<?php
$pageTitle = 'Page 2';
include 'header.php'
?>

<div>My content</div>

<?php include 'footer.php' ?>

header.php

<html>
    <head>
        <title> My Site : <?php echo $pageTitle ?> </html>
    </head>
<body>

footer.php

</body>
</html>
webbiedave
Oh, i guess i type slow... : )
wretrOvian
A: 

If i were to add some code before including the header, will it help?

<?php
    $currentPage = "Random Page Title";
    include "header.php";
?>

And then use the value in header.php so print the page title?

wretrOvian
+1  A: 

webbiedave's answer is perfectly fine, but in the long run, you should really learn to use either a decent template language (Smarty, Twig), or a PHP framework that has it's own templating. Kohana and Codeigniter are both pretty easy to get into.

Bopp
Agreed. As his experience and needs progress, he should make the leap. My answer was just a simple starting point.
webbiedave
A: 

Yes, it will help definitely. But you need to do a little customization.

First of all, make sure that you connect to the database, if you want to query / fetch data from database. For this to happen, include the "config.php" page at the very beginning of the script, in which your database connection logic will be present.

Then, write your query to fetch data from that database, and assign that value to the required variable for using it in the header page.

Lastly, include your "header.php" page.

For "config.php" page:-

Logic of Database Connection, like using of "mysql_connect()" & "mysql_select_db()" functions.

For "custom.php" page:-

<?php
  include "config.php";

  $sql = "SELECT pageTitle FROM db_table WHERE condition = 'something'";
  $sql_exe = mysql_query($sql) or die("Error in Fetching Page Title");
  if( mysql_num_rows($sql_exe) ) {
    $currentPage = mysql_result($sql_exe, 0, 0);
  }
  else {
    $currentPage = "Random Page Title";
  }
  mysql_free_result($sql_exe);

  include "header.php";
?>

Also, if you want, you can always use some class for mysql connection & queries, to fetch data. But this is how it always work.

Knowledge Craving