Dynamically change the title of the page with PHP - php

I have a blog and I would like the tag in the head section of the HTML document to change dynamically using PHP. Here is my PHP code:
<?php
session_start();
if(isset($_SESSION['admin']) and !empty($_SESSION['admin'])){
echo 'Logout';
}
require('mysql2.php');
//Displaying the information from the DB to the user
//with pagination, i.e different pages
function post(){
$sp_query = mysql_query("SELECT COUNT(id) FROM posts");
$pages = ceil(mysql_result($sp_query, 0) / 1);
$page = (isset ($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * 1;
$query = mysql_query("SELECT id,title, article, datetime
FROM posts ORDER BY id DESC LIMIT $start, 1 ");
//Check if there are any rows in the DB
if(mysql_num_rows($query)){
while($result = mysql_fetch_assoc($query)){
//displaying the results
echo '<article class="blog-post">
<div class="blog-info">
'.stripslashes($result['title']).' ';
echo
stripslashes($result['datetime']).'<div>';
echo
nl2br(stripslashes($result['article'])).'</article>';
$title[] = $result['title'];
$id =
mysql_real_escape_string((int)$result['id']);
echo '<input type="hidden"
value="'.$result['id'].'" />';
$_SESSION['post_id'] = $id;
//If the admin is logged in, session variables
//for editing and deleting a post must be set
//and the conforming links should be displayed
if(isset($_SESSION['admin']) and
!empty($_SESSION['admin'])){
//$_SESSION['post_id'] = $id;
$_SESSION['edit_post'] = $id;
echo '<article class="blog-post">';
echo '<a href="delete.php"
id="delete" onclick="return del();">Delete this post</a>';
echo '<br />Edit this post';
echo '</article>';
}
}
}
//The drop down menu
function options(){
$new_query = mysql_query("SELECT title FROM posts
ORDER BY id DESC");
$num = 1;
while($array = mysql_fetch_assoc($new_query)){
echo '<option
value="blog.php?page='.$num++.'">'.$array['title'].'</a></option>';
}
}
?>
And here is the HTML:
<?php require('mysql2.php');
require('blog_process.php');
?>
<!DOCTYPE html>
<html>
<head>
<!--Meta Data-->
<meta charset="utf-8">
<meta name="description" content="About Chris Shilts">
<meta name="author" content="Chris Shilts">
<meta name="keywords" content="chris, shilts">
<meta name="viewport" content="width=device-width, initial-scale=1,
maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<!--css-->
<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="style.css">
<!-- Javascript -->
<script type="text/javascript" src="delete.js"></script>
<!-- Favicons-->
<link rel="shortcut icon" href="favicon.ico">
<!--Title-->
<title id="title"><?php //php code should go here?></title>
</head>
<body>
<!--Contains all content-->
<div id="container">
<!--Content at start of page, generally the same-->
<header>
<div id="logo">
Hello There!
</div>
<!--Primary Navigation-->
<nav>
Link
Link
Link
</nav>
</header>
<!--Blog Posts-->
<?php post();?>
<!-- The navigation bar for the blog posts -->
<select onclick="navigation();" id="select">
<option value="" selected="selected"></option>
<?php options(); ?>
</select>
<!--First Footer-->
<footer id="footer-one">
Site Design By Chris Shilts | Programming by
Stefany Dyulgerova
</footer>
<!--Second Footer-->
<footer id="footer-two">
<a href="http://www.w3.org/html/logo/">
<img id="html5" src="http://www.w3.org/html/logo/badge
with CSS3 / Styling">
</a>
</footer>
<!--/container-->
</div>
</body>
</html>
I have also have a mysql database and here are the fields there:
id title article dateime
Please help me!
I tried to put the $result['title'] into a an array like this
$title[] = $result['title'];
And then to loop it through in the element based on the based on the id in the $_SESSION['post_id'] but the problem is that I have to reload the page twice in order the title to take effect.

Trying to save the blog title in an array isnt't work for you because the $title variable is only accessible within the post function.
You could have post return the $title array...
//initialize the array at the beginning of the post function like so
$title = array();
//return the array at the end of the function like so
return $title;
Then in the page, you'd replace
<?php post();?>
With
<?php $title = post();?>
However, You need $title BEFORE you the call to post. So that won't really help you.
I would suggest...
1) Create a Class Object with a global title variable. Have an initialize function to handle the database call. Then make post a function on the class that prints out the page HTML.
2) Create a title function that returns the correct page title and call it like so..
<title id="title"><?php get_page_title(); ?></title>
Update:
In your php file add the following function after the options function:
public function get_page_title() {
//add code to get the page title
// not sure what title you want since you are showing multiple posts on one page
}

Here is the code snippit that needs to be fixed : <title id="title"><?php echo $result['title']; ?></title>
This will work if there is one title, otherwise take the first : <title id="title"><?php echo $result['title'][0]; ?></title>

Related

Is there a way to automatically use another image as a temporary placeholder for missing images sitewide?

I am working on building a site, but right now it has several images that I don't have actual images for yet. As this site has thousands of images or places where images should be, I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?
Update: Since I am still a bit confused as to where to even place this function, I am going to add the code for one of the pages that I need this for then maybe someone can help me figure out how to place it.
Here is the code for one of the pages:
<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>
<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>
<body>
<div class="wrapper">
<a id="top"></a>
<?php require_once('header.php'); ?>
<?php require_once('nav.php'); ?>
<div class="category"><h2>Flower Trees</h2></div>
<div class="display">
<?php do { ?>
<ul>
<li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
<br />
<span class="name"><?php echo $row_master['name']; ?></span></a></li>
</ul>
<?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
<!-- end .display --></div>
<?php
mysqli_free_result($master);
?>
<?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
Since this is as simple as a foreach loop, and not tons of images scattered across your webpage, you can use something like:
$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
Full code:
<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>
<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>
<body>
<div class="wrapper">
<a id="top"></a>
<?php require_once('header.php'); ?>
<?php require_once('nav.php'); ?>
<div class="category"><h2>Flower Trees</h2></div>
<div class="display">
<?php do {
$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
?>
<ul>
<li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="<?php echo $image; ?>"/>
<br />
<span class="name"><?php echo $row_master['name']; ?></span></a></li>
</ul>
<?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
<!-- end .display --></div>
<?php
mysqli_free_result($master);
?>
<?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?
Such a function might be written as:
function im($imgName) {
$pathToImgs = "images/";
if (file_exists( $pathToImgs . $imgName )) {
echo $pathToImgs . $imgName;
}
else {
echo $pathToImgs . "placeholder.jpg";
}
}
Then in your html:
<img src="<?php im("product1.jpg"); ?>">
<img src="<?php im("product2.jpg"); ?>">
<img src="<?php im("product3.jpg"); ?>">
As a start.
***Edit 1:
Given your code where it says:
<img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
You might modify it with a conditional that inserts the placeholder image in the event that the target image simply doesn't exist, yet.
<img class="thumb" src="<?php
if (file_exists("img/" . $row_master['img'])) {
echo "img/" . $row_master['img'];
}
else {
echo 'img/placeholder.jpg';
}
?>">
You could reuse this functionality by turning the conditional into a php function, so described as a starter above.
Using jQuery, you can accomplish something easy enough using a global $('img') handler when errors occur. Simply swap them out with your placeholder image afterwards.
$('img').on('error', function() {
const oldSrc = encodeURIComponent($(this).attr('src'));
$(this).attr('src', `https://via.placeholder.com/300/000000/FFFFFF/?text=${oldSrc}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="imagethatdoesntexist.jpg"><br />
<img src="anotherimage.jpg">
Here I use placeholder.com (A convenient site for placeholder images such as this), and inject the old image source into the query string, which the site will render in the image itself.

Make dynamic page with database?

Here's what I'm trying to do. I'm trying to echo blog posts stored in my database. Simple enough, but I want them to be redirected to view_post.php to show the full post, when they click on the little preview. Here's my code:
<?php
session_start();
require_once('required/db.php');
$_SESSION['admin'] = false;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>WillWam - Blog</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/style.css" type="text/css">
<link rel="ico" href="assets/favicon.ico">
</head>
<body>
<nav><h2 class="title">The Blog</h2></nav>
<?php
$sql="SELECT id,title,author,body FROM posts ORDER BY id DESC";
if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf('<div class="row"><div class="row-inner"><p><strong>%s</strong> | %s |</p></div></div>', $row[0],$row[1],$row[2]);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
<div class="top-margin wrapper"><div class="container"><p>Administrator? Click here.</p></div></div>
</body>
</html>
How would I go about making the preview row a link dynamically (such as view_post.php?id=1)? What would I put in view_post.php?
Assumming on $row the id is contained you can create the links like this
printf('<a href="view_post.php?id='.$row['id'].'"> <----just put the id there
And on view_port use the value
<div class="row"><div class="row-inner">
<p><strong>%s</strong> | %s |</p></div></div></a>', $row[0],$row[1],$row[2]);

Dynamically generated "submit" buttons in PHP

First time posting here (so please be gentle, as I am a relative PHP newbie).
I am building an intranet for our company and one of the things I need to do is to create a form that lists all outstanding sales orders (pulled from our accounting database) and provides a "submit" button beside each one to create the relevant work order.
Here is the code:
<div class="report_column">
<div class="report_header">
<div class="report_column_title" style="width:150px;margin-left:5px">ship date</div>
<div class="report_column_title" style="width:200px">customer</div>
<div class="report_column_title" style="width:140px;text-align:right">item</div>
<div class="report_column_title" style="width:120px;text-align:right">quantity</div>
</div>
<?php
// Open connection
include 'includes/dbconnect.php';
// Perform query
$result = mysqli_query($con,"SELECT * FROM tSalOrdr ORDER BY dtShipDate ASC");
// Retrieve results
while($row = mysqli_fetch_array($result)) {
$order = $row['lId'];
if ($row['bCleared'] == 0) {
$shipdate = substr($row['dtShipDate'], 0,10);
$customer = $row['sName'];
$po = $row['sComment'];
echo '<div class="report_item" style="width:750px";>';
echo '<form class="form" action="index.php?page=form&item=create_work_order" method="POST">';
echo '<div class="report_item_date" style="width:120px">'.$shipdate.'</div>';
echo '<div class="report_item_name" style="width:530px">'.$customer;
echo '<input type="hidden" name="po" value="'.$po.'" />';
echo '<input type="submit" class="submit" style="height: 25px;width:100px;margin:0px;padding:0px;margin:0px" value="work order"/>';
echo '</div>';
$result2 = mysqli_query($con,"SELECT * FROM tSOLine WHERE lSOId=$order ORDER BY sDesc ASC");
while($row = mysqli_fetch_array($result2)) {
if ($row['dRemaining'] <> 0) {
echo '<div class="report_item_details">';
echo '<div class="report_item_item">'.$row['sDesc'].'</div>';
echo '<div class="report_item_quantity">'.$row['dRemaining'].'</div>';
echo '</div>';
}
}
echo '</form>';
echo '</div>';
}
}
// Close connection
mysqli_close($con);
?>
</div>
What happens when I do this is that the first "submit" button will, for some reason, send me back to "index.php". The other buttons will load the correct page, however, they do not POST the required value.
Is there something I am doing wrong or is this something that needs different methodology than what I am currently using? My research on this seems to indicate that perhaps I should use javascript or an array to deal with this, but, having never dealt with either, I am not sure how to proceed. Any pointers would be appreciated.
Thanks.
#maniteja: The index.php is as follows:
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="language" content="en" />
<title></title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<link href="css/forms.css" rel="stylesheet" type="text/css" />
<link rel="icon" type="image/ico" href="favicon.ico" />
<script type="text/javascript" src="scripts/jquery-2.1.0.min.js" ></script>
<script type="text/javascript" src="scripts/tabcontent.js" ></script>
</head>
<body>
<!-- BEGIN MAIN CONTENT -->
<div id="wrapper">
<!-- BEGIN HEADER -->
<div id="header">
<img src="images/logo.jpg">
</div>
<!-- END HEADER -->
<!-- BEGIN MAIN MENU -->
<div id="leftcolumn">
<?php include 'includes/menu.php'; ?>
</div>
<!-- END MAIN MENU -->
<!-- BEGIN CONTENT FRAME -->
<div id="rightcolumn">
<div id="content_area">
<?php
if (isset($_GET['page']))
{$page = $_GET['page'];
include('pages/' . $page . '.php');}
else {include('pages/home.php');}
?>
</div>
</div>
<!-- END MAIN CONTENT -->
</body>
</html>
I've made seventeen other forms with it, so I don't think that it is the problem. I'm hoping that this is just a typo or a logic error on my part.
u can use
<button type='submit' class='' name='' onclick=''>Submit</button>
Try to do onclick. See my example below.
input type="button" name="submit" onclick='location.href="index.php?id=$id"'
AS far as I understand, you are making your forms go to index.php:
echo '<form class="form" action="index.php?page=form&item=create_work_order" method="POST">';
Can you explain what is your expected behavior when a button is pushed?

The PHP code stops after the > in the if statement

For some reason my html stops recognizing the code for php after the first and second >, at the point marked with the comment code stops here.
The meaning for this that I need to get a picture from the database and then show it on the website as a header. I am very new to PHP and HTML. I am using phpmyadmin and sublimetext. the database is called stickerdome with the table images. in images there are 3 columns: id, name, link.
This is my code:
<head>
<?php
//Database Connect
$connect = mysql_connect("localhost","root","");
//Database Select
$db = mysql_select_db("stickerdome",$connect);
?>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title> StickerDome </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="banner">
<?php
//Query
$query1 = mysql_query("SELECT * FROM images WHERE id = 1");
$num = mysql_num_rows($query1);
if ($num > 0) // code stops here right after the >
{
while ($output1 = mysql_fetch_assoc($query1))
{
$src = $output1['link'];
echo "<img src='".$src."' alt='Image1'>"; //code stops here right after the > for the second time
}
}
else
{
echo "No picture found.";
}
?>
</div>
This is the file in total:
<!DOCTYPE html>
<html>
<head>
<?php
//Database Connect
$connect = mysql_connect("localhost","root","");
//Database Select
$db = mysql_select_db("stickerdome",$connect);
?>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title> StickerDome </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="banner">
<?php
//Query
$query1 = mysql_query("SELECT * FROM images WHERE id = 1");
$num = mysql_num_rows($query1);
if ($num IS NOT NULL)
{
while ($output1 = mysql_fetch_assoc($query1))
{
$src = $output1['link'];
echo "<img src='".$src."' alt='Image1'>";
}
}
else
{
echo "No picture found.";
}
?>
</div>
<div id="navigation">
<ul>
<li>
<a class="first" href="index.html">StickerDome</a>
</li>
<li>
<a class="second" href="samplepack.html">Sample Pack</a>
</li>
<li>
<a class="second" href="contact.html">Contact</a>
</li>
</ul>
</div>
<div id="pagename"><img src="Stickedomepagename.png"></div>
<div id="text">
<h1>Welcome to Stickerdome</h1>
<p class="text">Stickerdome is a website that gives you the best stickers you could ever imagine. It gives you <br>
- the best quality for every sticker <br>
- the best endurance that is usable outside <br>
- the biggest assortment <br>
<br>
For several years stickers started to became more popular. Everyone starting loving stickers. You can place them almost everywhere imaginable. But there is still one thing that nobody had and that is their own stickers. Yes, your own stickers! You can design your own stickers, send them to us, and we make sure that your stickers will be on your doormat within 5 days! Every design is possible, from round to square to with a border or without. You say it we make it!
</p>
</div>
</body>
<footer>
<p class="footer"> Stickerdome 2014 | Netherlands</p>
</footer>
</html>
you could try a different method or debug your sql.
Since i see your dutch im providing you with a link to a tutorial which greatly helped me the first time i worked with sql. maybe if you follow it you can fix your problem.
http://www.phphulp.nl/php/tutorial/overig/pdo-verbinden-met-verschillende-databases/534/inleiding/1364/

$wpdb->get_results() as an array of arrays

I am adding an ancillary page to my wordpress site ( without the site's styling, menu, etc ) using the following template and it is not returning any results from the database. I've read countless web pages and a couple of WP books and I am at a lost. I can see the four records in the database but the page shows none. Here's my template:
<?php
/*
Template Name: Media Player Page
*/ ?><!DOCTYPE html> >
<head>
<meta charset="<?php bloginfo('charset'); ?>" />
<title>Online Media Player</title>
<?php wp_head(); ?>
<link rel="stylesheet" href="/assets/css/music-player.css" type="text/css" media="screen" charset="utf-8">
<script src="/assets/js/jquery-1.8.3.js"></script>
</head>
<body>
<div class="main-center">
<h1>Please select your choice of music</h1>
<?php
global $wpdb;
$rows = $wpdb->get_results("select * from ppm_playlists");
foreach($rows as $row) :
?>
<a class="openplayer" data-genre="<?php echo $row['id']; ?>" href="#"><?php echo $row['playlist']; ?></a>
<?php endforeach; ?>
</div> <!-- /.main-center -->
<script type="text/javascript">
(function($) {
$('.main-center').on('click', '.openplayer', function(e){
var genre = $(this).data('genre');
e.preventDefault();
alert(genre);
});
})(jQuery);
</script>
</body> </html>
$wpdb->get_results will return an array of objects, not an array of arrays, unless you pass it a second parameter instructing otherwise. If you had debugging enabled, you would see Fatal Error: Cannot use object of type stdClass as array....
You want to be using object syntax:
foreach($rows as $row) : ?>
<a class="openplayer" data-genre="<?php echo $row->id; ?>" href="#"><?php echo $row->playlist; ?></a>
<?php endforeach; ?>
Or pass a second parameter to get_results
$rows = $wpdb->get_results("select * from ppm_playlists", ARRAY_A);

Categories