Hey I've recently been making a website and want to display the data from my database in a grid format opposed to it just listing down the page.
Here is my code right now:
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
I was wondering how I would go about creating a for loop to allow the data from this database in conjunction with the image to span across the page with 7 columns and however many rows down until it reaches the end of the database.
Thanks!
<?php
$query = "Select * from tablename";
$bind = $conn->query($query);
if ($bind->num_rows > 0){
while ($row = $bind->fetch_assoc()){
?>
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
<?php
}
}
?>
Try this, I just add while loop until End Of file (EOF table)
So have the following while loop which will output all the results for a SQL query carried out in PHP:
while ($row = mysqli_fetch_array($result))
{
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
$output = "Resturant Name: $restaurant_name <br /> Cusine: $cusine <br /> Average Wait Time: $wait_time";
echo "$output";
}
You can assume that $result will contain the table which I am reading on row at a time. The above code is working just fine but when I try to display the information in HTML (so that it actually looks nice) I run into a problem
If I do the following:
<html>
<section id="main" class="container 75%">
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<?php echo $output; ?>
</div>
</section>
</html>
It will only display the very last resort. I know that this happening because $output can only hold one string at a time, but I don't know any other way to display the information on the HTML. I though of possibly using an array to store all the strings, but the documentation doesn't show me how to set-up a dynamic array.
Does anyone here know how to display all the results of the search query in an HTML page?
You can do combine both php and html code like this:
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<?php
while ($row = mysqli_fetch_array($result)) :
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
$output = "Resturant Name: $restaurant_name <br /> Cusine: $cusine <br /> Average Wait Time: $wait_time";
echo "<div class=\"box\">$output</div>";
endwhile;
?>
This way you don't have to use an array to display the result.
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<?php
while ($row = mysqli_fetch_array($result)) {
$row = mysqli_fetch_array($result);
echo 'Restaurant name: '.$row['restaurant_name'];
echo 'Cusine: '.$row['cusine'];
// ...and so on
}
?>
</div>
You can have the loop produce the HTML inside your div with a table. I am not sure what your CSS is like for your box class, but this will certainly make it look better while printing out all of your results.
<header>
<h2>Here Are Some Places You'd Like To Eat</h2>
</header>
<div class="box">
<table>
<tr>
<td>Restaurant</td>
<td>Cusine</td>
<td>Wait Time</td>
</tr>
while ($row = mysqli_fetch_array($result))
{
$restaurant_name = $row['restaurant_name'];
$cusine = $row['cusine'];
$wait_time = $row['wait_time'];
echo "<tr><td>". $restaurant_name . "</td><td>" . $cusine . "</td><td>" . $wait_time . "</td></tr>";
}
</table>
</div>
You are overwriting your $output variable every loop, and then trying to echo $output later; it will only contain the data from the last iteration.
Instead, make $output an array containing your data and then loop over it for display purposes:
$output=array();
while ($row = mysqli_fetch_array($result)) :
$output[]=$row;
endwhile
Then you can loop over the $output array to build an output for each restaurant:
foreach($output as $value):
$returnDetails='<div class="box">';
$returnDetails.='Resturant Name: '.$output['restaurant_name'].'<br />';
// etc. for all details
$returnDetails.='</div>';
echo $returnDetails;
endforeach;
Added benefit of this way: you have access to the $output array if you ever wanted to access a single row outside the context of the loop
I want to create an automatic cms in my website using php and mysql
i.e. I would just feed data to mysql table and it will generate result.
so my code is:
<!DOCTYPE html>
<html>
<head>
<?php
include 'head.php';
include 'conct.php';
?>
<title>GIZMOMANIACS|DOWNLOADS</title>
</head>
<body>
<div id="container" style="width:100%;height:100%;clear:both">
<div id="header" style="background-color:#FFFFFF;">
<div class="head" style="clear:both">
<a href= "http://gizmomaniacs.site88.net">
<img src="/GM%203D.gif" width= "200" height="100" alt='gizmomaniacs logo'></a></div>
<h1 style="margin-bottom:0; float:right"><font id="gmfont">GIZMOMANIACS</font></h1>
</div>
<div id="menu" style="clear:both;background-color:#0762AE">
<?php include 'head.html'; ?></div> <div class="content" >
<?php include 'search.php'; ?>
<ul>
<?php
$sql = "SELECT * from downloads";
$result = mysql_query($sql);
if($result==false){
$view = "error";
$error = "Could not retrieve values";
}
else {
$dload = $GET_['downloadname'];
$imagelink = $GET_['imagelink'];
$title = $GET_['title'];
while ($row = mysql_fetch_array($result))
{
echo "<li><a class =\"alldld\" href=\"$dload\" title=\"$title\"><img class=\"downloads\" src =\"$imagelink\"/>$title</a><br></li>";
}
}
?>
</ul>
</div>
<div class="social">
<?php
include 'social.php';
?></div>
</div>
</body>
</html>
everything is gong well but three thing are not happening they are:
a href atrribute not retreiving from db
a title atrribute not retreiving from db
img src atrribute not retreiving from db
in the actual source it is showing
<a class ="alldld" href="" title=""><img class="downloads" src =""/></a><br></li>
<li><a class ="alldld" href="" title=""><img class="downloads" src =""/></a>
the src href title attribute are blank
so what to do?
change this part of code
$dload = $GET_['downloadname'];
$imagelink = $GET_['imagelink'];
$title = $GET_['title'];
while ($row = mysql_fetch_array($result))
{
echo "<li><a class =\"alldld\" href=\"$dload\" title=\"$title\"><img class=\"downloads\" src =\"$imagelink\"/>$title</a><br></li>";
}
to
while ($row = mysql_fetch_array($result))
{
$dload = $row['downloadname'];
$imagelink = $row['imagelink'];
$title = $row['title'];
echo "<li><a class =\"alldld\" href=\"$dload\" title=\"$title\"><img class=\"downloads\" src =\"$imagelink\"/>$title</a><br></li>";
}
While retrieving from DB you need to use the array in which the values are fetched and not the $_GET array. also there is no such thing as $GET_.
Important Note: Stop using mysql_ function and start using mysqli_* functions or PDO.For more info see here
You're outputting the rows like this:
$dload = $GET_['downloadname'];
$imagelink = $GET_['imagelink'];
$title = $GET_['title'];
while ($row = mysql_fetch_array($result))
{
echo "<li><a class =\"alldld\" href=\"$dload\" title=\"$title\"><img class=\"downloads\" src =\"$imagelink\"/>$title</a><br></li>";
}
}
There's a couple of issues with that. First of all, if you wanted to retrieve it from the query string, you'd want to use $_GET, not $GET_. Second, you don't want to retrieve it from the query string with $_GET; you want to retrieve it from $row. Thirdly, you need to put it inside the while loop. Once you've fixed that, it should work.
$_GET is the array containing values passed in the URL.
<?php
// Let's take the following URL
// http://localhost/index.php?name=John&age=20
echo $_GET["name"]; // Will display 'John'
echo $_GET["age"]; // Will display '20'
?>
When you select something from the database, the variable $row contains each line of the results that you get using the function mysql_fetch_array. Try this to display your data :
<?php
// ...
while ($row = mysql_fetch_array($result)) {
$dload = $row["downloadname"];
$imagelink = $row["imagelink"];
$title = $row["title"];
echo "<li><a class =\"alldld\" href=\"$dload\" title=\"$title\"><img class=\"downloads\" src =\"$imagelink\"/>$title</a><br></li>";
}
?>
I'm trying to make a image search. it will be showing images of movies and i also want the movie name to show below the image. this is what i got far
In my phpMy i got 5 rows
id int(11)
title varchar(100)
description text
url text
keywords varchar(100)
Here is my search bar
<div>
<form action='/search.php' method='GET' style="margin-bottom:1px;">
<input id='searchbar' type='text' size='65' name='search' placeholder="search for movies & tv shows">
<input id='submit' type='submit' name='submit' value='Search' >
</form>
</div>
and this is the results page
<html>
<head>
<title>FastMegaMedia</title>
<link rel="icon" href="img/putlockermedia_logo.png" type="image/icon">
<link rel="stylesheet" href="Style/index.css" media="screen">
</head>
<body>
<?php include_once("/php/header.php"); ?>
<table id=content width="100%" height="25" border="0" cellpadding="0" cellspacing="0">
<?php include_once("/php/ad1.php"); ?>
<td width="63%" valign="top">
<section class="content"> <!-- start of conntent -->
<?php
$x = 0;
$construct = '';
$button = $_GET ['submit'];
$search = $_GET ['search'];
if(!$button)
echo "you didn't submit a keyword";
else
{
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_connect("localhost","root","");
mysql_select_db("search");
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="keywords LIKE '%$search_each%'";
else
$construct .="AND keywords LIKE '%$search_each%'";
}
$construct ="SELECT * FROM searchengine WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>.</br></br><li>
Try more general words. for example: If you want to search 'how to create a website'
then use general keyword like 'create' 'website'</li><li> Try different words with similar
meaning</li><li> make sure you are spelling is correct</li>";
else
{
echo "$foundnum results found !<p>";
while($runrows = mysql_fetch_assoc($run))
{
$title = $runrows ['title'];
$desc = $runrows ['description'];
$url = $runrows ['url'];
echo "
<a href='$url'><b>$title</b></a><br>
$desc<br>
<a href='$url'></a><p>
";
}
}
}
}
?>
</section> <!-- end of conntent -->
</td>
<?php include_once("/php/ad2.php"); ?>
</table>
</body>
</html>
what could I do to make it show images instead of just showing the tittle, i know i'm missing something.. i'm new to this btw be nice
First, you appear to be vulnerable to SQL injection attacks. Never trust unsanitized user-input data.
Well, you need to store the image somewhere (I'd store it on disk with the path/file name stored in the database as type varchar), then in your PHP code where you output the title, description, and URL, just also query the database for the image path and <img src... that.
You missed the images and the references to them (if they exists in your database):
echo "
<a href='$url'><b>$title</b></a><br>
$desc<br>
<a href='$url'></a><br>
<img class='images' src='$srcOfFoundImage' title='$titleOfFoundImage'><p>
";
If you dont have the images, you can ask Google to find them.
I wish to set the title of my webpage to Ultan.me - Whatever the post title. I want it to display the post title. The posts are submitted to a MySQL database and the title row is called "title". Any help is appreciated with this small question.
Update:
Here is the page itself now but it doesn't display the title. Should I open the php document and connect to my database somewhere different to it's current locations?
The Code (The only necessary piece is the beginning):
<html>
<head>
<meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
<title>Ultan.me - <?echo $title;?></title>
<link rel="stylesheet" href="css/styles.css" type="text/css" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript"
src="js/jquery.labelify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(":text").labelify();
});
</script>
<style>
a {text-decoration:none}
</style>
</head>
<body>
<div id="main">
<!-- Menu Start -->
<div id="menu">
<ul>
<li>home</li>
<li>about me</li>
<li>archives</li>
<li>contact</li>
<li>gallery</li>
</ul>
</div>
<!-- Menu End -->
<img src="images/banner.png" />
<div id="content">
<div id="posts">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('ultankc');
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid ID specified.");
}
$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";
$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", $row['timestamp']);
$title = stripslashes($row['title']);
$entry = stripslashes($row['entry']);
$get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $row[category]");
$category = mysql_fetch_array($get_categories);
?>
<p><?php echo "<p id='post-title'><strong>" . $title . "</strong></p>"; ?><br /><br />
<div id="entry"><?php echo $entry; ?>
</div><br /><br />
<p id="date">Posted in <?php echo $category['category_name']; ?> on <?php echo $date; ?></p>
</p>
<h2 id="share-title">Share This Post</h2>
<div id="social-share">
<li id="link-right"><a href="http://twitter.com/home?status=
I just read <?php echo $title; ?> at http://ultan.me/post.php?id=<?php echo $id; ?>"><center>Twitter</center></a></li>
<li id="link-left"><center>Digg</center></li>
<br>
<li id="link-right"><center>Facebook</center></li>
<li id="link-left"><a href="http://www.google.com/buzz/post?url=http://ultan.me/post.php?id=<?php echo $id; ?>
"><center>Google Buzz</center></a></li>
<div class="clr"></div>
</div>
<h2 id="comments-title">Comments</h2>
<div id="comment-list">
<?php
}
$commenttimestamp = strtotime("now");
$sql = "SELECT * FROM php_blog_comments WHERE entry='$id' ORDER BY timestamp";
$result = mysql_query ($sql) or print ("Can't select comments from table php_blog_comments.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$timestamp = date("l F d Y", $row['timestamp']);
printf("<div class='comment-ind'><p id='comments'><a id='username' href=\"%s\">%s</a> %s</p>", stripslashes($row['url']), stripslashes($row['name']), $timestamp);
print("<p class='comments'>" . stripslashes($row['comment']) . "</p><div class='clr'><br></div></div>");
}
?>
<div class="clr"></div>
<form id="commentform" method="post" action="process.php">
<p><input type="hidden" name="entry" id="entry" value="<?php echo $id; ?>" />
<input type="hidden" name="timestamp" id="timestamp" value="<?php echo $commenttimestamp; ?>">
<input type="text" name="name" id="name" title="Name (required)" /><br />
<input type="text" name="email" id="email" title="Mail (will not be published) (required)" /><br />
<input type="text" name="url" id="url" title="Website" value="http://" /><br />
<br />
<textarea title="Your Comment Goes Here" name="comment" id="comment"></textarea></p>
<p><input type="submit" name="submit_comment" id="submit_comment" value="Add Comment" /></p>
</form>
</div>
<div id="pages">
<?php
$total_results = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS num FROM php_blog"));
$total_pages = ceil($total_results['num'] / $blog_postnumber);
if ($page > 1) {
$prev = ($page - 1);
echo "<< Newer ";
}
for($i = 1; $i <= $total_pages; $i++) {
if ($page == $i) {
echo "$i ";
}
else {
echo "$i ";
}
}
if ($page < $total_pages) {
$next = ($page + 1);
echo "Older >>";
}
?>
</div>
</div>
</div>
<!-- Sidebar Start -->
<div class="sidebar">
<!-- Item 1 -->
<div id="side-item">
<h2>
<a href="http://www.dailybooth.com/UltanCasey">
<img src="images/db-icon.jpg">Dailybooth
</a></h2>
<div id="side-item-content">
<center>
<img src="http://dailybooth.com/UltanCasey/latest/medium.jpg" />
</center>
</div>
</div>
<!-- Item 2 -->
<div id="side-item">
<h2><img src="images/connect.jpg" />Connect</h2>
</div>
<div id="side-item-content">
<div class="tweet-title"><p>Latest Tweet:</p></div>
<div id="tweet">
<?php
function getTwitterStatus($userid){
$url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=1";
function auto_link_twitter ($text)
{
// properly formatted URLs
$urls = "/(((http[s]?:\/\/)|(www\.))?(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
$text = preg_replace($urls, " <a href='$1'>$1</a>", $text);
// URLs without protocols
$text = preg_replace("/href=\"www/", "href=\"http://www", $text);
// Twitter usernames
$twitter = "/#([A-Za-z0-9_]+)/is";
$text = preg_replace ($twitter, " <a href='http://twitter.com/$1'>#$1</a>", $text);
// Twitter hashtags
$hashtag = "/#([A-Aa-z0-9_-]+)/is";
$text = preg_replace ($hashtag, " <a href='http://hashtags.org/$1'>#$1</a>", $text);
return $text;
}
$xml = simplexml_load_file($url) or die("could not connect");
foreach($xml->status as $status){
$text = $status->text;
}
echo auto_link_twitter ($text);
}
getTwitterStatus("UltanKC");
?>
</div>
<br>
<ul>
<li id="social">YouTube</li>
<li id="social">Twitter</li>
<li id="social">LastFM</li>
<li id="social">Email</li>
</ul>
</div>
<!-- Item 2 End-->
<div id="side-item">
<h2><img src="images/archive.jpg" />Archives</h2>
</div>
<div id="archive-side">
<?php
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('ultankc');
$result = mysql_query("SELECT FROM_UNIXTIME(timestamp, '%Y') AS get_year, COUNT(*) AS entries FROM php_blog GROUP BY get_year");
while ($row = mysql_fetch_array($result)) {
$get_year = $row['get_year'];
$entries = $row['entries'];
echo "<li id='tag'>Entries from " . $get_year . " (" . $entries . ")<br /></li>";
}
$result1 = mysql_query("SELECT * FROM php_blog_categories ORDER BY category_name ASC");
while($row = mysql_fetch_array($result1)) {
$result2 = mysql_query("SELECT COUNT(`id`) AS entries FROM php_blog WHERE category = $row[category_id]");
$num_entries = mysql_fetch_array($result2);
echo '<li id="tag">' . $row['category_name'] . ' (' . $num_entries['entries'] . ')</li>';
}
?>
</div>
</div>
<div class="clr" />
</div>
<!-- Sidebar End -->
<div id="footer">
<p> © Ultan Casey 2010</p>
<p style="margin-top: -18px; float:right">Home | About Me | Email Me</p>
</div>
</div>
</div>
</body>
</html>
?>
Here's the method I use (for similar things, not just title):
<?
ob_start (); // Buffer output
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title><!--TITLE--></title>
</head>
<body>
<?
$pageTitle = 'Title of Page'; // Call this in your pages' files to define the page title
?>
</body>
</html>
<?
$pageContents = ob_get_contents (); // Get all the page's HTML into a string
ob_end_clean (); // Wipe the buffer
// Replace <!--TITLE--> with $pageTitle variable contents, and print the HTML
echo str_replace ('<!--TITLE-->', $pageTitle, $pageContents);
?>
PHP usually works be executing any bits of code and printing all output directly to the browser. If you say "echo 'Some text here.';", that string will get sent the browser and is emptied from memory.
What output buffering does is say "Print all output to a buffer. Hold onto it. Don't send ANYTHING to the browser until I tell you to."
So what this does is it buffers all your pages' HTML into the buffer, then at the very end, after the tag, it uses ob_get_contents () to get the contents of the buffer (which is usually all your page's HTML source code which would have been sent the browser already) and puts that into a string.
ob_end_clean () empties the buffer and frees some memory. We don't need the source code anymore because we just stored it in $pageContents.
Then, lastly, I do a simple find & replace on your page's source code ($pageContents) for any instances of '' and replace them to whatever the $pageTitle variable was set to. Of course, it will then replace <title><!--TITLE--></title> with Your Page's Title. After that, I echo the $pageContents, just like the browser would have.
It effectively holds onto output so you can manipulate it before sending it to the browser.
Hopefully my comments are clear enough.
Look up ob_start () in the php manual ( http://php.net/ob_start ) if you want to know exactly how that works (and you should) :)
You parse the field from the database as usual.
Then let's say you put it in a variable called $title, you just
<html>
<head>
<title>Ultan.me - <?php echo htmlspecialchars($title);?></title>
</head>
EDIT:
I see your problem. You have to set $title BEFORE using it. That is, you should query the database before <title>...
header.php has the title tag set to <title>%TITLE%</title>; the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later. then, you use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
For more reference, click PHP - how to change title of the page AFTER including header.php?
What about using something like:
<?php
$page_title = "Your page tile";
include("navigation.php"); // if required
echo("<title>$page_title</title>");
?>
Move the data retrieval at the top of the script, and after that use:
<title>Ultan.me - <?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>
You need to set the value of $title before echoing it.
Also, you should really sanitize any data before using it in queries as this is a security risk
create a new page php and add this code:
<?php
function ch_title($title){
$output = ob_get_contents();
if ( ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/");
$replacements = array("<title>$title</title>");
$output = preg_replace($patterns, $replacements,$output);
echo $output;
}
?>
in <head> add code: <?php require 'page.php' ?> and on each page you call the function ch_title('my title');
The problem is that $title is being referenced on line 5 before it's being assigned on line 58. Rearranging your code isn't easy, because the data is both retrieved and output at the same time. Just to test, how does something like this work?
Because you're only retrieving one row, you don't need to use a while loop, but I left it with hopes that it'll make it easier for you to relate to your current code. All I've done is removed the actual output from your data retrieval, and added variables for category and category name which are then referred to as usual later on. Also, I haven't tested this. :)
It'll be tricky to rearrange your code to make this work, but I'll try :)
So, put this at the top of your code:
<?php require_once('mysql.php'); ?>
The top of the file should look like:
<?php require_once('mysql.php'); ?>
<html>
<head>
<meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
<title>Ultan.me - <?php echo htmlspecialchars($title); ?> </title>
Then, create a file called mysql.php in the same directory that the file which contains the code you quoted is in.
Put this is mysql.php:
<?php
mysql_connect ('localhost', 'root', 'root');
mysql_select_db ('ultankc');
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
die("Invalid ID specified.");
}
$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";
$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());
$res = mysql_fetch_assoc($result);
$date = date("l F d Y", $res['timestamp']);
$title = $res['title'];
$entry = $res['entry'];
$get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $res['category']");
$category = mysql_fetch_array($get_categories);
?>
Well, hope that helped :)
I know this is an old post but having read this I think this solution is much simpler (though technically it solves the problem with Javascript not PHP).
<html>
<head>
<title>Ultan.me - Unset</title>
<script type="text/javascript">
function setTitle( text ) {
document.title = text;
}
</script>
<!-- other head info -->
</head>
<?php
// Make the call to the DB to get the title text. See OP post for example
$title_text = "Ultan.me - DB Title";
// Use body onload to set the title of the page
print "<body onload=\"setTitle( '$title_text' )\" >";
// Rest of your code here
print "<p>Either use php to print stuff</p>";
?>
<p>or just drop in and out of php</p>
<?php
// close the html page
print "</body></html>";
?>
Simply add $title variable before require function
<?php
$title = "Your title goes here";
require("header.php");
?>
header.php
<title><?php echo $title; ?></title>
<?php echo APP_TITLE?> - <?php echo $page_title;?>
this should work fine for you
if you want to current script filename as your title tag
include the function in your project
function setTitle($requestUri)
{
$explodeRequestUri = explode("/", $requestUri);
$currentFileName = end($explodeRequestUri);
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $currentFileName);
$explodeCurrentFileName = explode("-", $withoutExt);
foreach ($explodeCurrentFileName as $curFileValue)
{
$fileArrayName[] = ucfirst($curFileValue);
}
echo implode(" ", $fileArrayName);
}
and in your html include the function script
and replace your title tag with this
<title>Your Project Name -
<?php setTitle($_SERVER['REQUEST_URI']); ?>
</title>
it works on php7 and above but i dont have any idea about php 5.*
Hope it helps