tags:

views:

43

answers:

2

header.php

<?php

$conn = mysql_connect('localhost', '-', '-');
@mysql_select_db('accmaker', $conn) or die("Unable to select database");

?>

<html>
<head>
<title>Mysite.com - <?php isset($pageTitle) ? $pageTitle : 'Home'; ?></title>
</head>
<body>

profile.php

require 'header.php';

$q = mysql_query("SELECT * FROM users WHERE username = '$username'");

$r = mysql_fetch_assoc($q);

$pageTitle = "Profile of $r[username]";

I think you understand what i want

I cant include header.php after the query, because i wont be connected to mysql

waht do you suggest other than having the connection snippet on every page

+4  A: 

What do I suggest? A MVC (Model-View-Controller) Framework like Kohana. If you don't want to go that route, break your connection off into its own file:

<?php

  # connect
  require_once("connection.php");

  # load page data array
  require_once("page-data.php");

?>
...
<title><?php print $page["title"]; ?></title>

Note here how I have a $page array of data. This will be helpful when debugging later rather than having several independent variables. With an array of page data, I can quickly see all of the information laid out for any given page:

print "<pre>";
print_r($page);
print "</pre>";

Determining your title should be done within page-data.php, rather than on your page:

$config["site_name"]   = "Bob's Shoe Mart";
$config["admin_email"] = "[email protected]";

/* query to get $row['title'] */

$page["title"] = (!empty($row["title"])) ? $row["title"] : $config["site_name"] ;
Jonathan Sampson
Yeah, definitely try to find a good MVC framework...but if you're stuck working on a legacy system...well, you're just out of luck sometimes.
Topher Fangio
Another thing to add (frameworks already do that) : buffer your output. So, the script ends before output start.With that, you won't have a database connexion open for 0.5s or more the client need to download the page.
Arkh
A: 

Not sure of a "best" solution, but we currently include multiple files. We have our "utilities.php" file that connects to the database and provides some nice functions. We then set our page titles and then we include "top.php" which is the layout portion. It doesn't have anything except HTML with a little bit of PHP for display purposes. Looks like this:

include "utilities.php";
$pageTitle = "Welcome";

include "top.php";
Topher Fangio