开发者

Dynamic titles best way?

header.php

<?php

$conn = mysql_connect('localhos开发者_StackOverflow中文版t', '-', '-');
@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


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"] = "bob@shoemart.com";

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

$page["title"] = (!empty($row["title"])) ? $row["title"] : $config["site_name"] ;


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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜