Can't print certain values from database in PHP - php

I'm using this database and I have created a table in my PHP file where I list all of these values. I have link my "subject" values to a different file which is supposed to display "description", but every time when I click on "Subject" I get the description from the first input in the table.
This is my code for displaying the table
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");
?>
<?php
ob_start();
include 'organize_meeting.php';
ob_end_clean();
$mysqli = new mysqli("localhost", "root", "", "users");
$curr_user = $loggedInUser->username;
mysql_connect('localhost', 'root', '');
mysql_select_db('users');
$query = "SELECT * FROM uc_messages WHERE `to` = '$curr_user'";
$records = mysql_query($query);
echo "
<body>
<div id='wrapper'>
<div id='top'><div id='logo'></div></div>
<div id='content'>
<h2>My Meetings</h2>
<div id='left-nav'>";
include("left-nav.php");
echo "
</div>
<div id='main'>
</div>
<div id='bottom'></div>
</div>
</body>
</html>";
?>
<table width = "600" border = "1" cellpadding = "1" cellspacing = "1">
<tr>
<th>From</th>
<th>Subject</th>
<th>Beginning of meeting</th>
<th>End of meeting</th>
</tr>
<?php
while($msgs = mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>".$msgs['from']."</td>";
echo "
<td>
<a href = 'info.php' target = '_blank_'> ".$msgs['subject']." </a>
</td>
</html>";
echo "<td>".$msgs['TimeFrom']."</td>";
echo "<td>".$msgs['TimeTo']."</td>";
echo "<tr>";
}
?>
And this is my code that is suppoused to display the description
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");
?>
<?php
ob_start();
include 'organize_meeting.php';
ob_end_clean();
$mysqli = new mysqli("localhost", "root", "", "users");
$curr_user = $loggedInUser->username;
mysql_connect('localhost', 'root', '');
mysql_select_db('users');
$query = "SELECT * FROM uc_messages WHERE `to` = '$curr_user'";
$records = mysql_query($query);
echo "
<body>
<div id='wrapper'>
<div id='top'><div id='logo'></div></div>
<div id='content'>
<h2>About Meeting</h2>
<div id='left-nav'>";
echo "
</div>
<div id='main'>
</div>
<div id='bottom'></div>
</div>
</body>
</html>";
?>
<?php
$msgs = mysql_fetch_assoc($records);
echo "<p>".$msgs['from']."</p>";
echo "<p>".$msgs['description']."</p>";
echo "<p>".$msgs['TimeFrom']."</p>";
echo "<p>".$msgs['TimeTo']."</p>";
?>
I always get the same description from the database, although I click on a different input.

Note: You are mixing up mysqli.* and the mysql together and you have to convert to mysqli.* the entire query that you have. You have to fix all the mix up codes that you have and after that you follow the code that i have given.
And the below example i am giving in the statement of the mysqli.* and you have to make changes to the code.
File One:
You are missing to pass the ID of the subject or the auto increment ID in the <a> tag which you want to display.
Hence the following <a> tag will be as follows.
Replace:
<td>
<a href = 'info.php' target = '_blank_'> ".$msgs['subject']." </a>
</td>
With:
<td>
<a href = 'info.php?subject_id=".$msgs['id']."' target = '_blank_'> ".$msgs['subject']." </a>
</td>
File Two:
Hence you can get the Request that we have passed in the <a> tag over here and we shall manipulate it.
$msgs = mysqli_fetch_assoc($records)
echo "<p>".$msgs['from']."</p>";
echo "<p>".$msgs['description']."</p>";
echo "<p>".$msgs['TimeFrom']."</p>";
echo "<p>".$msgs['TimeTo']."</p>";
Remove these lines since it makes no sense. Already you have connected to the DB using the mysqli connectivity.
mysql_connect('localhost', 'root', '');
mysql_select_db('users');
Change the query like this so that it will be the mysqli.* way.
$query = "SELECT * FROM uc_messages WHERE `id` = '".$_REQUEST['subject_id']."'";
$records = mysqli_query($mysqli,$query);

Related

PHP : $_GET is not retrieving data from MySQL database

I have a blog-type php site with mysql database. This blog have some lessons. There's a table "lessons", which contain id, title, text of lesson, etc.
When I display the last lessons on the main page, it works just right.
I connect to db like this:
<?php
$db = mysql_connect ("localhost", "root", "");
mysql_select_db("kursach", $db);
mysql_query("SET NAMES utf8");
$result = mysql_query ("SELECT title, meta_k, meta_d, text FROM settings
WHERE page='index' ", $db);
$myrow = mysql_fetch_array($result);
?>
and display them using loop:
<?php
$result = mysql_query("SELECT id, title, date, description FROM lessons", $db);
$myrow = mysql_fetch_array($result);
do {
printf ("<div class='right-column-content'>
<div class='right-column-content-heading'>
<a href='lesson_view.php?%s'><h1>%s</h1></a>
<h2>%s </h2>
</div>
<div class='right-column-content-content'>
<p>%s</p>
<div class='button'><a href='lesson_view.php?%s' >Читати далі</a></div>
</div>
</div>", $myrow['id'], $myrow["title"], $myrow["date"], $myrow["description"], $myrow["id"]);
}
while($myrow = mysql_fetch_array($result))
?>
I also have a file for full content of the lesson - lesson_view.php. As you can see at the code above, i send the id of lesson to link to this lesson:
lesson_view.php?%s
$myrow["id"]
In the lesson_view.php I connect to db and get the id like this:
<?php
$db = mysql_connect ("localhost", "root", "");
mysql_select_db("kursach", $db);
mysql_query("SET NAMES utf8");
if (isset($_GET['id'])) {$id = $_GET['id'];}
$result = mysql_query("SELECT * FROM lessons WHERE id = '$id' ", $db);
$myrow = mysql_fetch_array($result);
?>
And use this code to display the data:
<div class="right-column-content">
<div class="right-column-content-heading">
<h1><?php echo $myrow['title'] ?></h1>
<h2><?php echo $myrow['date'] ?> </h2>
<h2><?php echo $myrow['author'] ?> </h2>
</div>
<div class='right-column-content-content'>
<p><?php echo $myrow["text"] ?></p>
</div>
</div>
The problem is, when I try to look the full content of lesson (for exaple, /lesson_view.php?1), it doesn't display any data: no title, no text, nothing. I've tried this query directly at MySQL and it works, so, maybe there's some error in php code that I can't find. Will be thankful for any help.
P.S. I'm a beginner at php.
if you want to have in $_GET id then your link should be instead lesson_view.php?%s -> lesson_view.php?id=%s
for example lesson_view.php?id=5 mean that $id = $_GET['id'] will give 5, $id = 5;
<a href='lesson_view.php?%s'><h1>%s</h1></a>
You did not name the 'id' variable.
Change the links to
<a href='lesson_view.php?id=%s'><h1>%s</h1></a>
The only issue is that your printf() have 5 arguments and you are using only four and fourth one is description that you are using here
<div class='button'><a href='lesson_view.php?%s' >Читати далі</a></div>
Solution is that:
printf ("<div class='right-column-content'>
<div class='right-column-content-heading'>
<a href='lesson_view.php?%s'><h1>%s</h1></a>
<h2>%s </h2>
</div>
<div class='right-column-content-content'>
<p>%s</p>
<div class='button'><a href='lesson_view.php?id=%s' >Читати далі</a></div>
</div>
</div>", $myrow['id'], $myrow["title"], $myrow["date"], $myrow["id"], $myrow["description"]);
Move $myrow["id"] in fourth position you will get the ID as query string.
And also add the id in query string.

How do I put names from table into dropdown menu?

Im trying to figure out why the dropdown doesnt show up of the list of teachers in my tables
include"teacher.php"
<body onload="displayDate()">
<img src="Raw Pictures/Header.jpg" style="width:100% ; height:15%">
<img src="Raw Pictures/green.png" style="width:8%; height:11%; position:absolute; top:4% ;left: 3%">
<br><br><br><div>
Teacher:
<select>
<option>echo $row</option>
</select>
</body>
</html>
then the teacher.php
<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('teacher_account');
$sql = "SELECT facultyname FROM subj_eva";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {}
?>
I cant figure out how to show the teachers from database into dropdown box? how do I fix it?
You are probably looking for something like that:
<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('teacher_account');
$sql = "SELECT teachername,facultyname FROM subj_eva";
$result = mysql_query($sql);
?>
<html>
<body onload="displayDate()">
<img src="Raw Pictures/Header.jpg"
style="width:100% ; height:15%">
<img src="Raw Pictures/green.png"
style="width:8%; height:11%; position:absolute; top:4% ;left: 3%">
<div>
Teacher:
<select>
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value="<?= $row['teachername'] ?>">
<?= $row['teachername'] ?> (<?= $row['facultyname'] ?>)
</option>
<?php } ?>
</select>
</body>
</html>
Of course the code can be separated into files, I bundled it for the sake of readability here. It probably makes sense to move those styling rules into a separate css file instead of using those ugly inline styles.
A side note: you are using the outdated and deprecated mysql extension. You should switch to either mysqli or PDO and learn about the security advantages of "prepared statements". Also you should not use the root account for normal database use. Create a less privileged account and only use the root account for administrative tasks.
Try this
$sql = "SELECT facultyname FROM subj_eva";
$result = mysql_query($sql);
echo "<select>";
while ($row = mysql_fetch_array($result))
{
echo "<option>$row['column']</option>";}
echo "</select>";
?>
<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('teacher_account');
$sql = "SELECT facultyname FROM subj_eva";
$result = mysql_query($sql);
while ($result_array = mysql_fetch_array($result, MYSQL_ASSOC) ) {
$row = $row .'<option>'. $result_array["facultyname"] .'</option>';
}
?>
and php for generate html file
<?php
include"teacher.php";
?>
<body onload="displayDate()">
<img src="Raw Pictures/Header.jpg" style="width:100% ; height:15%">
<img src="Raw Pictures/green.png" style="width:8%; height:11%; position:absolute; top:4% ;left: 3%">
<br><br><br><div>
Teacher:
<select>
<?php
echo $row;
?>
</select>
</body>
</html>

How to display data twice from a mysql table in php

Im making a page that will display top ten voters in a table and show the number one voter aswell. I got the top ten table to work but I can't figure out how to get the second part to work. What would I do to get it to work where it would show the top voter in a img tag like this example
img src="https://minotar.net/avatar/TOPVOTERHERE"
First part
<div class="col-md-6">
<table class="table table-striped">
<tr>
<td><strong>Username</strong></td>
<td><strong>Votes</strong></td>
</tr>
<?php
$username2 = "exampleuser";
$password2 = "pass";
$hostname = "127.0.0.1";
$dbhandle = mysql_connect($hostname, $username2 , $password2)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("mc711",$dbhandle)
or die("Could not select database");
$result = mysql_query("SELECT * FROM GALTotals ORDER BY votes DESC");
$count = 0;
while ($row = mysql_fetch_assoc($result)) {
$count++;
if($count>10){
}else{
echo "<tr>";
echo "<td>".$row['IGN']."</td>";
echo "<td>".$row['votes']."</td>";
echo "</tr>";
}
}
?>
</table>
</div>
Second Part - This is the part I dont know how to do
<div class="col-md-6">
<center>
<img src="https://minotar.net/avatar/TOPVOTERHERE">
</center>
</div>
The simplest way to do it would be to create a variable to store the top voter data before you start your while loop. Then, in the while loop, you can set this variable if you're in the first iteration.
First part:
$result = mysql_query("SELECT * FROM GALTotals ORDER BY votes DESC");
$count = 0;
$topVoterIGN = NULL;
while ($row = mysql_fetch_assoc($result)) {
$count++;
if($count>10){
}else{
echo "<tr>";
echo "<td>".$row['IGN']."</td>";
echo "<td>".$row['votes']."</td>";
echo "</tr>";
if(is_null($topVoterIGN)) {
$topVoterIGN = $row['IGN'];
}
}
}
Second Part:
<div class="col-md-6">
<center>
<img src="https://minotar.net/avatar/<?php echo $topVoterIGN; ?>">
</center>
</div>
Alternatively, you can store the top 10 voters in an array and then retrieve the first item later.

update value from '0' to '1' on image click?

I'm new to php and mysql so sorry if i'm doing it wrong. i have a page on my site that lists the reviews that members give to other other users.
Basically i have approved and deleted in my database which means that after a user sends the review it has to be reviewed by the user before it gets displayed.
once the user clicks the approved image which is a tick it goes to approved_review.php and in their i have my sql code to update the value from 0 to 1 in my database.
It should work exactly the same for the delete but obviously instead of updating the approved column it will update deleted.
the code i have tried is not working i have been working on this for quite some time and can;t figure it out.
Can someone please tell me where i'm going wrong?
Heres the code:
<?php
$reviews_set = get_pending_reviews();
while ($reviews = mysql_fetch_array($reviews_set)) {
?>
<p> </p>
<div class="pending-review-content">
<?php
$date = $reviews['date_added'];
?>
<div class="prof-content-pend-reviews" id="reviews">
<div class="message_pic"><?php echo "<a href=\"profile.php?id={$reviews['from_user_id']}\">
<img width=\"50px\" height=\"50px\" src=\"data/photos/{$reviews['from_user_id']}/_default.jpg\" /></a>";?>
</div>
<div class="reviews-date"><? echo "$date"; ?></div>
<div class="reviews-from">
<?php echo "<a href=\"profile.php?id={$reviews['from_user_id']}\">{$reviews['display_name']}"; ?>
</a> Wrote:
</div>
<div class="reviews-content">
<?php echo "{$reviews['content']}"; ?>
</div>
</div>
<div class="reviews-approve">
<img src="assets/img/icons/tick.png" width="30" height="25" /></div>
<div class="reviews-delete">
<img src="assets/img/icons/cross.png" width="30" height="25" />
</div>
<? } ?>
approved_review.php function:
<?
$sql = "UPDATE `playtime`.`ptb_reviews` SET `approved` = '1' WHERE `ptb_reviews`.`id` =".$_SESSION['user_id']."";
echo "<div class=\"infobox1\">review approved.</div>";
?>
Your approach seems logical. After you loop through your reviews, you click on the tick or delete pngs to update or delete.
So, in approved_review.php
<?php
//you are missing the connection to your mysql database...
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$sql = "UPDATE `playtime`.`ptb_reviews` SET `approved` = '1' WHERE `ptb_reviews`.`id` =".$_SESSION['user_id']."";
//execute the mysql query
$r = mysql_query($sql);
if (!mysql_error())
{
echo "<div class=\"infobox1\">Review Approved.</div>";
}
?>
a little edit rrrfusco's post
// or die for details if mysql_query won't work correct
$r = mysql_query($sql) or die (mysql_error());

Set Page Title using 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

Categories