This question already has answers here:
Wrapping a div around every third item in a foreach loop PHP [closed]
(4 answers)
Group mysql results in groups of four
(1 answer)
Closed 2 years ago.
The below code does almost exactly what I want visually. Except Column 1 and Column 2 just show the same picture for all 10 entries, while Column 3 shows a unique entry every Row.
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Covid-Deaths</title>
<link rel="stylesheet" type="text/css" href="covid.css">
<script src="https://kit.fontawesome.com/1f285a5a86.js" crossorigin="anonymous"></script>
<script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>You're terrible at this</h1>
<p>Get each picture to be unique</p>
<?php
//database Connection
include 'dbconfig.php';
// retrieving data from table accounts
$query = "SELECT * FROM test_info where tf = 1 LIMIT 10";
$result = mysqli_query($conn, $query);
$query2 = "SELECT * FROM test_info where tf = 1 LIMIT 10 OFFSET 10";
$result2 = mysqli_query($conn, $query2);
$query3 = "SELECT * FROM test_info where tf = 1 LIMIT 10 OFFSET 20";
$result3 = mysqli_query($conn, $query3);
?>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($result2->num_rows > 0) {
while ($row2 = $result2->fetch_assoc()) {
if ($result3->num_rows > 0) {
while ($row3 = $result3->fetch_assoc()) {
?>
<div class="container">
<div class="card">
<a href="<?php echo $row['obit_url']; ?>"><img src="uploaded-images/<?php echo
$row['picture'];?>" width=80%/></a>
<h4><?php echo $row['names']; echo ", "; echo $row['age'];?></h4>
<p><?php echo " "; echo "State: "; echo $row['state']; ?></p>
</div>
<div class="card">
<a href="<?php echo $row2['obit_url']; ?>"><img src="uploaded-images/<?php echo
$row2['picture'];?>" width=80%/></a>
<h4><?php echo $row2['names']; echo ", "; echo $row2['age'];?></h4>
<p><?php echo " "; echo "State: "; echo $row2['state']; ?></p>
</div>
<div class="card">
<a href="<?php echo $row3['obit_url']; ?>"><img src="uploaded-images/<?php echo
$row3['picture'];?>" width=80%/></a>
<h4><?php echo $row3['names']; echo ", "; echo $row3['age'];?></h4>
<p><?php echo " "; echo "State: "; echo $row3['state']; ?></p>
</div>
</div>
<?php
}
}
}
}
}
}
?>
</body>
</html>
Example of what it outputs:
Steve Paul Mary
Steve Paul John
Steve Paul Sam
What I want it to look like:
Steve Paul Mary
Randy Kyle John
Phil Scott Sam
I can't seem to get the first and second column to pull in the unique entries that I know are there.
In the middle while loop, the first and second columns will stay the same as you don't fetch a new row for them.
You could change it to 1 while loop and just fetch the other rows in this 1 loop...
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$row2 = $result2->fetch_assoc();
$row3 = $result3->fetch_assoc();
this will fetch all 3 results in the same order. You would have to know what to do if any of them don't return a value though.
<?php
include_once("Globals.php");
global $model;
I want to capture the $order_id value from the $_GET['claim_order'] for future re-use.
if(isset($_GET['claim_order'])){
$order_id = $_GET['claim_order'];
}
for example the value saved in the $order_id variable is not available for repeat use on the current page.
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Caregiver Claims Order</title>
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Font Awesome -->
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
<!-- Google Font: Source Sans Pro -->
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
<!-- Main Sidebar Container -->
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<!-- Sidebar -->
<div class="sidebar">
<!-- Sidebar user (optional) -->
<div class="user-panel mt-3 pb-3 mb-3 d-flex">
<div class="info">
SESSION: Caregiver
</div>
</div>
<!-- Sidebar Menu -->
<nav class="mt-2">
<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
</ul>
</nav>
<!-- /.sidebar-menu -->
</div>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header" style="padding: 0px 0px 0px 0px" >
<div class="container-fluid " style="padding: 0px 0px 0px 0px" >
<div class ="row">
<div class="col">
<h1>Order#<?php
global $order_id;
echo (int)$order_id;
?></h1>
</div>
<div class ="col-auto">
<a href ="CaregiverCODetailView.php?button_claim=$care_giver_id">
<input type="submit" name="button_claim" class="btn btn-primary"></input>
</a>
<?php
if(isset($_GET["button_claim"])){
for example in the next 3 lines I try to use it but it returns the wrong value of 0 instead the correct value corresponding to the "button_claim".
I want to be able to refer to the value even if I refresh the .php page.
All I want to do is use that $order_id value in a SQL query. It basically indicates the ID# of the order in question.
$care_giver_id = $model->getCurrentUserId();
global $order_id;
$sql = "UPDATE `order` SET `care_giver_id` = '$care_giver_id' WHERE `order_id` = '$order_id'";
if(!mysqli_query($conn, $sql)){
header("Location: fail.php");
}else{
header("Location: CaregiverCODetailView.php");
}
}
?>
</div>
</div>
<div class="row" style="min-height:71vh" style="min-width:100vw">
<div class= "col" style="min-height:71vh" style="min-width:100vw">
<table id="example4" class="table table-borderless table-hover">
<?php
global $conn;
global $order_id;
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT";
$sql .= " `medication`.`name` as `name`,";
$sql .= " `medication`.`physical_form` as `form`,";
$sql .= " `medication`.`units` as `units`,";
$sql .= " `break_down`.`administer_time` as `time`,";
$sql .= " `break_down`.`quantity` as `quantity`";
$sql .= " FROM `break_down`";
$sql .= " JOIN `medication` on (`medication`.`medication_id` = `break_down`.`medication_id`)";
$sql .= " WHERE `break_down`.`order_id` = '$order_id'";
$result = $conn->query($sql);
echo "<id='example2'>";
echo "<tbody>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['quantity'] . $row['units']. "</td>";
echo "<td>" . $row['form'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "</tbody>";
echo "</table>";
echo "<h4>ORDERS DATABASE EMPTY</h4>";
}
?>
</div>
</div>
<div class="row" style="min-height:15vh" style="min-width:100vw">
<div class= "col" style="background-color:orange" style="min-height:15vh" style="min-width:100vw" >
<?php
global $conn;
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " select " ;
$sql .= " `patient`.`first` as `first`,";
$sql .= " `patient`.`last` as `last`,";
$sql .= " `order`.`order_id` as `order_id`,";
$sql .= " `order`.`date` as `datefield`";
$sql .= " from `patient`";
$sql .= " join `order` on (`order`.`patient_id` = `patient`.`patient_id`)";
$sql .= " where `order`.`order_id` = '$order_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div class='row '>";
echo "<div class ='col '>";
echo "<h3>Patient</h3>";
echo "<h5>" . $row['first'] . " " . $row['last'] . "</h5>";
echo "</div>";
echo "<div class = 'col-auto '>";
echo "<h3>Date Created</h3>";
echo "<h5>" . $row['datefield'] . "</h5>";
echo "</div>";
echo "</div>";
}
}
?>
</div>
</div>
</div>
<!-- /.container-fluid -->
</section>
</div>
</div>
<!-- ./wrapper -->
If you want to store some short-term data, PHP sessions would be a sufficient solution. Keep in mind that this data will only last as long as your session lasts.
session_start();
$_SESSION['order_id'] = $_GET['claim_order'];
For a longer-term storage solution, consider storing the data in a database like MySQL or in a file (make sure to keep this file out of the web directory if it's holding private information).
You can use the setcookie('name_of_cookie', $value); and get this data using $_COOKIE('name_of_cookie');. after this you can use the unset($_COOKIE('name_of_cookie'));
I have a database which contains 2 tables. In the second table there are numerous records and I'm trying to echo out the latest id (MAX id) to the page using PHP. There is something wrong with my code and I don't know what that is:
$sqlCount = "SELECT MAX(id) FROM records";
$sql = "SELECT id,preview,description FROM records";
$pn = (isset($_GET['pn'])) ? $_GET['pn'] : 1;
$res = upagination($con, $sql, $sqlCount, $pn, 6);
$list .="<table border=0>";
foreach ($res['rows'] as $row) {
$list .="<tr>";
$list .="<td>" . $row['id'] . "</td><td>" . $row['preview'] . "</td><td>" . $row['description'] . "</td>";
$list .="</tr>";
}
$list .="</table>";
$paginationCtrls = "";
if (isset($res['backLink'])) {
$paginationCtrls .= "Previous";
}
if (isset($res['numbers'])) {
foreach ($res['numbers'] as $number) {
if ($number === $res['current']) {
$paginationCtrls .= "$number";
}
(some deleted code to shorten this a little)
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css"></style>
<title>Humorweb</title>
<meta name="keywords" content="videos">
<meta name="description" content="Humorwebsite.org -collection of the funniest videos and photos from the internet!-">
<link rel="stylesheet" type="text/css" href="https://www.humorwebsite.org/style_main.css">
</head>
<body>
<div id="container">
<div id="logo"> </div>
<div id="sidebar">
<div id="links">
HOME
VIDEOS
PHOTOS
ABOUT
</div>
</div>
<div id="context">
<div id="context-text"></div>
<div id="context-kuva">
<br>
<div id="nakki">
<?php echo $list; ?>
</div>
</div>
</div>
</div>
The last row I'm trying to echo out is the $list variable, but I get nothing. I have made a CSS on this file and define width, height, position, and float properties, but end up getting nothing from database.
Now i dont know if this is simple or hard. If its just css or php code i need
But basically i have posting system and users can comment on posts. In the comments page it shows orginal post and one users have left (the comments)
I had one in there and this was fine but i added another and it looked like this...
[1]: http://i.stack.imgur.com/2fIXd.jpg
As you can see its completly different! Heres my code for it...
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
echo "<a href='Untitled9.php'>Go Back...</a>";
?>
<br/><br/>
<div class="message">
<?php
$sql = mysql_query("SELECT * FROM threads WHERE id = '".
mysql_real_escape_string($_GET['id']) . "'") or die(mysql_error());
while($r = mysql_fetch_array($sql)) {
$posted = date("jS M Y h:i",$r['posted']); echo "".$r['author']." $posted"; ?>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="<?php echo "".$r['message'].""; ?>">
Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<div class="message2"><?php echo " ".$r['message'].""; ?></div>
<?php echo "Likes: ".$r['votes_up']." "; echo "Dislike: ".$r['votes_down']."";>
</div>
<br/>
<hr width="725px">
<?php
echo "<h3>Replies...</h3>"; ?>
<div class="message"><?php
$sql = mysql_query("SELECT * FROM replies WHERE thread = '".
mysql_real_escape_string($_GET['id']) . "'") or die(mysql_error());
while($r = mysql_fetch_array($sql)) {
$posted = date("jS M Y h:i",$r['posted']); echo "".$r['author']." $posted"; ?>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="<?php echo "".$r['message'].""; ?>">
Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<div class="message2">
<?php echo " ".$r['message']."" ; } ?> </div>
</div>
<hr width="725px">
<form action="newreply.php" method="POST">
Your Name: <input type="text" name="author">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="thread"><br>
Message:<br><textarea cols="60" rows="5" name="message"></textarea><br>
<input type="submit" value="Post Reply">
</form>
The code looks really messy on here. I tried editing but couldnt get much better.
So bascially what i want to know is how do i prevent this (the overlapping) from happening?
Edit * CSS
.message {
width: 500px;
color: black;
background: white;
padding:8px;
border:1px solid white;
margin:5px auto;
-moz-border-radius:8px;
}
.message2 {
background-color: grey;
}
It looks to me as though everything is posting inside the second php function but i have some code pretty much the same for just the individual post and this displays normally i.e. as many as i want. Im just wondering is there something i need to add/change
Wrong (Your code):
<?php echo " ".$r['message']."" ; } ?> </div>
</div>
Correct:
<?php echo " ".$r['message']."" ; ?> </div>
</div>
<?php } ?>
You were opening multiple DIVs in your while loop but only closing two.
Similarly to Cobra_Fast's reply, it seems that the positioning of your divs seemed to be causing the problem, and also the position of your while loop.
Try replacing the replies section with the following and let me know if it is any better.
<?php
echo "<h3>Replies...</h3>";
$sql = mysql_query("SELECT * FROM replies WHERE thread = '".mysql_real_escape_string($_GET['id']) . "'") or die(mysql_error());
while($r = mysql_fetch_array($sql)) {
?>
<div class="message">
$posted = date("jS M Y h:i",$r['posted']);
echo $r['author']." ".$posted;
?>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-text="<?php echo $r['message']; ?>">
Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
</div>
<div class="message2">
<?php
echo " ".$r['message'];
?>
</div>
<?php
}
?>
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