I’d like to pull a value from my database and use it as the current page title. My connection works, the page loads fine, but I need access to a variable and I can’t figure this one out.
How my page is structured:
Blog.php
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/header.php');
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$blogid = $_GET['id'];
$stmt = $dbh->prepare("SELECT id, title, slug, body, image, author, date, category from blog WHERE id= :id ORDER BY date DESC");
$stmt->execute(array('id' => $_GET['id']));
$row = $stmt->fetch();
}
if(isset($row['title'])) {
$pageTitle = $row['title'];
} else {
$pageTitle = "Something Here";
}
$pageTitle is a variable in $header.php. It controls the <title> tage for each page.
Problem
My database connection $dbh is set in header.php. this means I don’t have access to $row['title'] until it’s too late.
Question:
How can I restructure this to gain access to $row['title'] BEFORE require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/header.php');. I really don’t want to pull the database connection out of the header if I don’t have to.
Thanks!
You can’t do that, because your
<title></tile>is already printed in the ouput.An hardcore fix would be to use rendering in buffer (with ob_start ob_get_content) then parse the rendered content to change the content of your
<title>tag.However the clever way is to get your database out of your header.
Regards