How to let the pagination keep the search parameters - php

Recently I am writing a products catalog for my company. I use the dropdown list to provide a filter to a grid views product list that has pagination. The filter is work fine if products not more than 1 page. When more then one page of search result, the browser will show all products same as no filter applied. Below is my code of the index.php. Please help because I already stuck in here for a week. Thank in advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?php session_start();
if (!isset($_SESSION['user_name']))
{
echo "<script>window.open('../login.php','_self')</script>";
}
$user_name=isset($_SESSION['user_name'])?$_SESSION['user_name']:'';
?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="css/gallery.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-3.2.1.min.js"></script>
<meta name="theme-color" content="#444" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php
include_once('../database/db_conection.php');//Include the database connection
?>
<div class="container">
<div class="col-md-2"> <br/>
<i class="fa fa-home" style="font-size:28px"></i>Home <br/>
<br/>
<br/>
<form action="buckle.php'" method="post" >
<div class="cf_header5">MATERIAL<br/>
(e.g.Brass, Alloy...)</div>
<select name="material" style="width:150px; height:25px;font-size:16px">
<option value="">Please select ....</option>
';
<?php
$sql_ml = "SELECT distinct material FROM products where material !='' order by material";
$records_ml=mysqli_query($dbcon,$sql_ml);
while ($row_ml=mysqli_fetch_array($records_ml)){
echo '<option value="'.$row_ml['material'].'">'.$row_ml['material'].'</option>';
}
?>
</select>
<br/>
<br/>
<div class="cf_header5">DESCRIPTION</div>
<select name="description" style="width:150px; height:25px;font-size:16px">
<option value="">Please select ....</option>
';
<?php
$sql_dn = "SELECT distinct catagory FROM products where catagory !='' order by catagory";
$records_dn=mysqli_query($dbcon,$sql_dn);
while ($row_dn=mysqli_fetch_array($records_dn)){
echo '<option value="'.$row_dn['catagory'].'">'.$row_dn['catagory'].'</option>';
}
?>
</select>
<br/>
<br/>
<div class="cf_header5">SIZE</div>
<select name="size" style="width:150px; height:25px;font-size:16px">
<option value="">Please select ....</option>
<?php
$sql_se = "SELECT distinct size FROM products where size !='' order by size";
$records_se=mysqli_query($dbcon,$sql_se);
while ($row_se=mysqli_fetch_array($records_se)){
echo '<option value="'.$row_se['size'].'">'.$row_se['size'].'</option>';
}
?>
</select>
<br/>
<br/>
<input type="submit" name="submit" value="Search" />
</form>
<?php //get the value from dropdown list and stored it to a variable
$material=isset($_POST['material']) ? $_POST['material'] : "";
$size=isset($_POST['size']) ? $_POST['size'] : "";
$description=isset($_POST['description']) ? $_POST['description'] : "";
?>
</div>
<div class="col-md-10">
<div id="main">
<header>
<div class="logo-outer">
<div class="logo"> <img src="../images/logo4.png" /> </div>
<?php
//////SET UP THE TOTAL images PER PAGE & CALCULATIONS:
$per_page = 12;// Number of images per page, change for a different number of images per page
// Get the page and offset value:
if (isset($_GET['page'])) {
$page = $_GET['page'] - 1;
$offset = $page * $per_page;
}
else {
$page = 0;
$offset = 0;
}
//Display no of items in cart
echo '<a href="viewcart.php?page=';echo $page+1;echo '&type=buckle';echo'">';
echo "You have";
$t_sql="select count(product_id) as nocart from cart where user_name='$user_name'";
$t_run=mysqli_query($dbcon,$t_sql);
$t_row=mysqli_fetch_array($t_run);
$cart_count=$t_row['nocart'];
echo '&nbsp';
echo '<span class="badge" >';echo $cart_count; echo '</span>';
echo ' items on list</a>';
//end of display number of items in cart
?>
</div>
</div>
</header>
<div class="margin">
<div id="pagination"><!-- #pagination start -->
<?php
$images_sql="select count(id) from products where product_type='buckle'";
if(isset($_POST['material'])and $material!='')
{$images_sql=$images_sql." and material='$material'";}
if(isset($_POST['description'])and $description!='')
{$images_sql=$images_sql." and catagory='$description'";}
if(isset($_POST['size'])and $size!='')
{$images_sql=$images_sql." and size='$size'";}
$images_sql=$images_sql." ORDER by id ASC";
$result_images = mysqli_query($dbcon, $images_sql);
$row_images = mysqli_fetch_array($result_images);
$total_images = $row_images[0];
// Calculate the number of pages:
if ($total_images > $per_page) {//If there is more than one page
$pages_total = ceil($total_images / $per_page);
$page_up = $page + 2;
$page_down = $page;
$display ='';//leave the display variable empty so it doesn't hide anything
}
else {//Else if there is only one page
$pages = 1;
$pages_total = 1;
$display = ' class="display-none"';//class to hide page count and buttons if only one page
}
////// DISPLAY THE PAGE COUNT AND BUTTONS:
echo '<h2'.$display.'>Page '; echo $page + 1 .' of '.$pages_total;//Page out of total pages
$i = 1;//Set the $i counting variable to 1
echo '<div id="pageNav"'.$display.'>';// $display variable will do nothing if more than one page
// Show the page buttons:
if ($page) {
echo '<button><<</button>';//Button for first page [<<]
echo '<button><</button>';//Button for previous page [<]
}
for ($i=1;$i<=$pages_total;$i++) {
if(($i==$page+1)) {
echo '<button class="active">'.$i.'</button>';//Button for active page, underlined using 'active' class
}
//In this next if statement, calculate how many buttonso show.
if(($i!=$page+1)&&($i<=$page+3)&&($i>=$page-1)) {//This is set for two below and two above the current page
echo '<button>'.$i.'</button>'; }
}
if (($page + 1) != $pages_total) {
echo '<button>></button>';//Button for next page [>]
echo '<button>>></button>';//Button for last page [>>]
}
echo '</div>';// #pageNav end
?>
</div>
<div id="gallery"><!-- Gallery start-->
<?php
// DISPLAY THE images:
//Define the SQL statement based on the dropdown list
if ($total_images>0)
{
$img_sql="select * from products where product_type='buckle'";
if(isset($_POST['material'])and $material!='')
{$img_sql=$img_sql." and material='$material'";}
if(isset($_POST['description'])and $description!='')
{$img_sql=$img_sql." and catagory='$description'";}
if(isset($_POST['size'])and $size!='')
{$img_sql=$img_sql." and size='$size'";}
$img_sql=$img_sql." ORDER by id ASC LIMIT $offset, $per_page";
$result = mysqli_query($dbcon, $img_sql);
while($row = mysqli_fetch_array($result)) {//Open the while array loop
//Define the image variable:
$image=$row['images'];
$product_id=$row['product_id'];
$product_type=$row['product_type'];
$size=$row['size'];
$material=$row['material'];
$description=$row['catagory'];
echo '<div class="img-container">';
echo '<div class="img">';
echo '<img src="images/'.$image.'">';
echo '</a>';
echo '</div>';
echo $product_id;echo '&nbsp &nbsp ';
echo 'Add to List';
echo '<br/>Size:';echo $size;
echo '&nbsp &nbsp Material: '; echo $material ;
echo '<br/>Description: ';echo $description;
echo '</div>';// .img-container end
}//Close the while array loop
}
else
{
echo'<br/><br>';
echo '<h1>Sorry! No result is matched, please search again.</h1>';
echo'<br/><br>';
}
?>
</div>
<!-- Gallery end-->
<div class="clearfix"></div>
</div>
</div>
<!-- #main end -->
</div>
</body>
</html>

Your logic seems OK but your problem is when you navigate trough pages you make a new call of the document, which doesn't include variables like filters but the current page ($_GET['page']).
Either you send filters as variables trough URL as well, which isn't the cleanest way to do table pagination.
Or you gather results in a javascript array, and then on click on a pagination button display the previous/next rows. By doing this you also avoid refreshing the whole document every time, which isn't necessary.

Related

How to create a variable with a value of its self + another variable

I need my carts page to be able to remember the total price of items, I have 3 items and they are all the same price (to make things simpler on my self). A user can submit the quantity using a form on another page. What I need the code to do remember the quantity for item 1, then when item 2 is submitted via the form it will add the quantity of the previous with the quantity submitted by the new item. So far iv gotten it to send the quantity through the form into the array, then it can be called whenever it's needed, but I can't figure out how I'm supposed to make it add the previous qty with the new one to give me a total price.
I don't think all the code is needed to help with this so I'll just post what I think is needed. If you want to see it all though just ask and I'll edit my post to include it.
My code:
<link id='stylecss' type="text/css" rel="stylesheet" href="css/cartstyle.css">
<link id='stylecss' type="text/css" rel="stylesheet" href="css/style.css">
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php
session_start();
?>
<?php
require_once("head.php");
?>
<?php
require_once("nav.php");
?>
<?php
var_dump ($_POST);
if(!isset($_SESSION['cart'])) {
$_SESSION['cart']=[];
}
$cart = &$_SESSION['cart'];
$movieName = $_POST['movie_name'];
$quantity = $_POST['qty'];
if(isset($moveName)) {
$currentQuantity = $cart[$movieName];
$cart[$movieName] = $currentQuantity + $quantity;
} else {
$cart[$movieName] = $quantity;
}
var_dump($_SESSION);
?>
<div class="shopping-cart">
<!-- Title -->
<div class="title">
Shopping Bag
</div>
<!-- Product #1 -->
<div class="item">
<div class="image">
<?php
foreach ($cart as $movieName=> $quantity) {
if ($movieName == 'Inception') {
echo '<img src="incepcart.jpg" alt="got"/>';
}
}
?>
</div>
<div class="description">
<?php
foreach ($cart as $movieName=> $quantity) {
if ($movieName == 'Inception') {
echo "<p>" . $movieName . "x" . $quantity;
}
}
?>
</div>
</div>
<!-- Product #2 -->
<div class="item">
<div class="image">
<?php
foreach ($cart as $movieName => $quantity) {
if ($movieName == 'Game of Thrones: Season 1') {
echo '<img src="gotcart.jpg" alt="got"/>';
}
}
?>
</div>
<div class="description">
<?php
foreach ($cart as $movieName => $quantity) {
if ($movieName == 'Game of Thrones: Season 1') {
echo "<p>" . $movieName . "x" . $quantity;
}
}
?>
</div>
</div>
<!-- Product #3 -->
<div class="item">
<div class="image">
<?php
foreach ($cart as $movieName=> $quantity) {
if ($movieName == 'Friends Season 1') {
echo '<img src="friendscart.jpg" alt="got"/>';
}
}
?>
</div>
<div class="description">
<?php
foreach ($cart as $movieName=> $quantity) {
if ($movieName == 'Friends Season 1') {
echo "<p>" . $movieName . "x" . $quantity;
}
}
?>
</div>
</div>
<div class="rhsidee">
<?php
if ($movieName == 'Game of Thrones: Season 1') {
}
$total = $_POST['qty'] * 19.99;
echo "<p>Total <span class\"price\" style=\"color:black\"><b>$total</b></span>"
?>
</div>
<?php
echo $currentQuantity * 20
?>
</div>
</div>
</div>
<form action="product.php">
<button class="prod" type="submit">Continue Shopping </button>
</form>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br>
<?php
require_once("footer.php");
?>
And the code for one of my forms that submits data into cart.php:
<form action="carttest.php" method="post">
<input type="hidden" name="movie_name" value= "Game of Thrones: Season 1" />
<input type = "hidden" name = "id" value = "M01" />
<br>
</select>
<div class="widthc">
<button class="prod" id="minus">−</button>
<input type="number" name="qty" value="0" id="qty" min="0" max="15"/>
<button class="prod" id="plus">+</button>
<br><br>
<button class="prod" type="submit"> Submit</button>
</form>
As mentioned by #sudhansu, Session is the best option here, What you can do here is create a session's key-value pair per item.
for e.g. onsubmit a quantity for item_CNT you just set a session value with following keys in it.
$_SESSION[itemCNT][quantity] = 100;
$_SESSION[itemCNT][name] = 'name';
$_SESSION[itemCNT][id] = 71273928739;
you can increment CNT as an when user adds quantity for a particular item.
You can loop through the SESSION array whenever you need it. you can access this session from any page.
To save those cart value. You can do it in three ways.
Session
Cookie
Db
If you want to keep track on user's cart. you can create cart table. and put the value of quantity and item id inside the cart page. and if you need value for a specific session, just store it inside session. and if you want to store it inside user's browser. just store it in cookie.

php - for loop takes only the first value from mysql result

In this code I'm trying to create as many modal boxes as the rows of my query result. This works! Then I want to fill these modal boxes with as many checkboxes as the number $row['seats_no'] from database. Here we have a problem..in every modal box it creates the same amount of checkboxes as the first one. What I mean is that the $row['seats_no'] has the number from the first row in every row.
<?php
session_start();
if(!isset($_SESSION['name']) && !isset($_SESSION['email']) && !isset($_SESSION['id']) && !isset($_SESSION['cash'])){
header("location: Start.php");
}
$name=trim($_SESSION['name']);
$email=trim($_SESSION['email']);
$dbc = mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($dbc,"SET NAMES 'utf8'");
mysqli_query($dbc,"SET CHARACTER SET 'utf8'");
if (isset($_POST['buy']) && isset($_POST['consert_id'])){
$q = "SELECT ticket_id, section, cost, seats_no FROM tickets INNER JOIN concert ON tickets.consert_id=concert.concert_id WHERE concert.concert_id=".$_POST['consert_id'];
//ticket_id, concert_id, section, cost, seats_no, concert_id,concert_name, date, place, category, description
$r = mysqli_query($dbc,$q);
$num= mysqli_num_rows($r);
$q1 = "SELECT * FROM concert WHERE concert_id=".$_POST['consert_id'];
$r1 = mysqli_query($dbc,$q1);
$first = mysqli_fetch_assoc($r1)
?>
<!DOCTYPE html>
<html>
<title>Seats</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link type="text/css" rel="stylesheet" href="seats_style.css">
<body>
<div style="z-index:1;position:fixed;">
<ul>
<li>E-Viva</li>
<li>Ανανεωση υπολοιπου</li>
</ul>
</div>
<div class="background">
<div class="transbox">
<div class="w3-container">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/199011/concert.png">
<h1><?=$first['concert_name']?></h1>
<div style="left:0;"><?=$first['date']?></div>
<div style="right:0;"><?=$first['place']?></div>
<p><?=$first['description']?></p>
<?php
while ($row = mysqli_fetch_array($r)) {
?>
<div style="margin-left:5em;padding:5px;"><?=$row['section']?></div>
<div style="margin-left:5em;padding:5px;">Τιμή <?=$row['cost']?>€</div>
<div style="margin-left:5em;padding:5px;"><button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Κράτηση</button></div>
<div id="id01" class="w3-modal" background="black">
<div class="w3-modal-content">
<div class="w3-container">
<span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-display-topright">×</span>
<p><h2>Διαλεξε τις θεσεις που θες</h2></p>
<form action="buy.php" method="post">
<table>
<?php
$num=0;
for($j=1; $j<=10; $j++){
echo "<tr>";
for($i=1; $i<= $row['seats_no']/10; $i++){
$num++;
echo "<td><input class='seat' type=\"checkbox\" name=\"s[]\" id=\"".$num."\" value=\"".$num."\"><label for=\"".$num."\">".$num."</label><input type='hidden' name='ticket_id' value='".$row['ticket_id']."'><input type='hidden' name='cost' value='".$row['cost']."'></td>";
}
echo "</tr>";
}
echo "</table><input class=\"ok\" type=\"submit\" name=\"ok\" value=\"Κράτηση\"></form></div></div></div><br>";
}
}
mysqli_free_result($r1);
mysqli_free_result($r);
mysqli_close($dbc);
?>
</div>
</div>
</div>
</body>
</html>
here are the results i get from executing my query at phpMyAdmin
Here are the buttons I create to open the modals
And here is the modal from the last button i clicked that in the database shows it should be 60 checkboxes but it shows 180
Κατερίνα,
Try to change the while ($row = mysqli_fetch_array($r)) {...} with a foreach loop,
like as foreach( mysqli_fetch_array($r) as $row ) {....}
Just a thought.
Also, you close one bracket too soon, remove one before the first mysqli_free_result($r1) and close it after the closing html tag </html> at the end of the file.
Also, as #tadman said, do some research and use parameterized queries. Your code it's very prone to MySQL Injections and you will face several problems. As far as i can see that page has to do with payments, or pre-payment.
Anyways, i hope i helped you.
Καλή επιτυχία ;)

php MYSQL query "ORDER BY" not working

Forewarning: I'm sure my code is clunky and inefficient, please feel free to call me out on it. I'm fairly new at this.
I'm attempting to order my query results by a column, indicated as a result of a select input. The select input exists on feed.php which features include: 'feedphp2.php.
The select input auto-submits onchange with action="feedSort.php". feedSort.php takes the submitted value and redirects to feed.php?sort=submittedValue. Then the included feedphp2.php within feed.php takes the $_GET['sort'] value and pulls a query sorted by that column.
//feed.php
<?php
session_start();
if(!isset($_SESSION['userID'])) {
header('Location: login.html');
}
?>
<html>
<head>
<title>Title</title>
<link href="style.css" type="text/css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css
family=Josefin+Sans:400,100,300,600,700' rel='stylesheet' type='text/css'>
</head>
<body style="background-color:rgba(0,212,242,0.1)">
<div class="headerSmall">
<div class="container">
<a href="index.php"><img class="logoImgSmall"
src="images/logosmall2.png"></a>
<div class="navFeed">
<?php include 'usernameGet.php';?>,Log Out
List a Meal
Dashboard
</div>
</div>
</div>
<div class="container">
<div class="sort">
<form action="feedSort.php" method="POST">
<select name="sortForm" onchange="this.form.submit()">
<option value="">Sort By...</option>
<option value="user">By User</option>
<option value="dateAdded">By Date Added</option>
</select>
</form>
</div>
<?php include 'feedphp2.php'?>
</div>
</body>
</html>
space
//feedphp2.php
<?php
include 'MysqlConnect.php';
mysqli_select_db($conn,$dbname);
if (isset($_GET['sort'])) {
$sortBy = $_GET['sort'];
echo $sortBy;
$resultQuery = "SELECT * FROM meals
ORDER BY '$sortBy'";
} else {
echo 'sortBy is not set.';
$resultQuery = "SELECT * FROM meals
ORDER BY user";
}
$result = mysqli_query($conn, $resultQuery);
//Write to divs
while ($rows = mysqli_fetch_assoc($result)) {
$imgSrc = $rows['image'];
echo '<a href="meal.php?'.'mealID=';
echo $rows['ID'];
echo '">';
echo '<div class="entry">';
echo '<div class="foodPic">';
echo '<img src="';
echo $imgSrc;
echo '">';
echo '</div>';
echo '<p class="entryName">'.$rows['mealName'].'</p>';
echo '<p class="entryServ">'.$rows['mealQuan'].'</p>';
echo '<p
class="entryPrice">$'.$rows['mealDollars'].'.'.$rows['mealCents'].'</p>';
echo '<img class="servingsIco" src="images/servings.png">';
echo '<p class="user">'.$rows['user'].'</p>';
echo '</div>';
echo '</a>';
}
?>
space
//feedSort.php:
<?php
session_start();
$sortBy = $_POST['sortForm'];
header ("Location: feed.php?sort=".$sortBy."");
?>
Columns within my table exist for both user and dateAdded and sort perfectly when explicitly provided within the query ie: SELECT * FROM meals
ORDER BY user. While provided through a PHP variable however:
Where $sortBy = user returns the exact same sort order as $sortBy = dateAdded.
I appreciate any help you might provide.
you using $_POST method to pass the value and using $_GET method to retrieve it . and change the $sortby without quotes. edit these lines in your feedphp2.php
<?php
include 'MysqlConnect.php';
mysqli_select_db($conn,$dbname);
if (isset($_POST['sort'])) {
$sortBy = $_POST['sort'];
echo $sortBy;
$resultQuery = "SELECT * FROM meals
ORDER BY $sortBy";
} else {
or use $_REQUEST[],Method which will retrieve both get and post method
<?php
include 'MysqlConnect.php';
mysqli_select_db($conn,$dbname);
if (isset($_REQUEST['sort'])) {//request method
$sortBy = $_REQUEST['sort'];//
echo $sortBy;
$resultQuery = "SELECT * FROM meals
ORDER BY $sortBy";
} else {

Selecting table and trying to query results with PHP is not working

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.

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