The PHP code stops after the > in the if statement - php

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/

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.

HTML Page trying to get information from php / mysql

This fairly simple issue is vexing me. I have an html page laid out with CSS. I have a simple php page that returns the latest record from a mysql site. I need to display this information in the html page in the "leftContent" div.
working 'latest.php' page is:
<?php
/*
Return the latest date and record for the left pane.
*/
include 'ESP8266_dbLogin.php';
$result = mysqli_query($link, "SELECT * FROM `thLog` ORDER BY logID DESC LIMIT 1") or die ("Connection error");
while($row = mysqli_fetch_array($result)) {
echo "Date: " . $row['logDate'] . "<br>";
echo "lightVal: " . $row['lightVal'];
}
mysqli_close($link);
?>
'index.html' code is as follows, with the target DIV of contentLeft for the php variables:
<!DOCTYPE html>
<!-- Basic Layout -->
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Sparks - Monitor</title>
<link rel="stylesheet" type="text/css" href="css/default.css">
<link href='//fonts.googleapis.com/css?family=Baloo' rel='stylesheet'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript" src="data24.js" ></script>
</head>
<body>
<div id="wrapper">
<div id="main">
<div id="banner">
<div id="bannerLeft">
<img class="bannerImg" alt="ESP8266 Logo" src="images\imgESP8266.png">
</div>
<div id="bannerRight">
<img class="bannerImg" alt="Settings Icon" src="images\imgGear.png">
</div>
<div id="bannerMain">
<h1>SPARKS Energy Monitor - Home</h1>
</div>
</div>
<div class="content" id="contentLeft">
<h2>Current Usage:</h2>
<p> The current lightVal and date should be here<p>
</div>
<div class="content" id="contentRight">
Generating chart, please wait...
</div>
</div>
</div>
</body>
<html>
Any help is gratefully received on the most efficient way to get the php variables (lightVal) into the html page. I know, stupid question!!
1) Rename your index.html to index.php
2) Replace your target div with your PHP code:
<div class="content" id="contentLeft">
<h2>Current Usage:</h2>
<?php
/*
Return the latest date and record for the left pane.
*/
include 'ESP8266_dbLogin.php';
$result = mysqli_query($link, "SELECT * FROM `thLog` ORDER BY logID DESC LIMIT 1") or die ("Connection error");
while($row = mysqli_fetch_array($result)) {
?>
<p class="dateClass"><?=$row['logDate']?></p>
<p class="lightValClass"><?=$row['lightVal']?></p>
<?
}
mysqli_close($link);
?>
</div>
It should be enough, just call index.php from browser.

Unexpected T_CONSTANT_ENCAPSED_STRING Error in PHP/MySQL

So I'm trying to run a query in PHP and while the query has no errors itself (or so it seems), the editor sees an error in an "echo" statement. The code is this:
<?php
include("include/session.php");
?>
<?php
$db = new PDO('mysql:host=localhost;dbname=cvtool;charset=utf8', 'user', 'pass'); // change these to your own database details
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // later, change ERRMODE_WARNING to ERRMODE_EXCEPTION so users wont see any errors
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$department = isset($_GET['department'])? $_GET['department']: null;
$sql = 'SELECT *
FROM education
WHERE school LIKE ?;
$q = $conn->prepare($sql);
$q->execute(array('%$department%');
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()) {
echo sprintf('%$department', $r['school']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!--The viewport tag is used in order to scale the page properly inside any screen size -->
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>CV Tool</title>
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="css/main.css"/>
<!--Import JQuery from stored file -->
<script src="js/jquery-1.11.1.min.js"></script>
<!--Import JQuery from Google's Content Delivery Network -->
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">-->
<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="js/menu.js"></script>
<script type="text/javascript" src="js/backToTop.js"></script>
</head>
<body>
<!--Big wrapper contains the whole site (header,navigation menu,....,footer-->
<div id="big_wrapper">
<header id="top_header">
<img src="images/cvlogo.png">
</header>
<br>
<nav class="clearfix">
<ul class="clearfix">
<li>Home</li>
<?php
/**
* User has already logged in, so display relavent links, including
* a link to the admin center if the user is an administrator.
*/
if($session->logged_in){
echo "<li>Search</li>"
."<li>My CV(s)</li>"
."<li>My Account</li>"
;
echo "<li>Logout</li>";
}
else
?>
</ul>
Menu
</nav>
<section id="main_section">
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Department</th>
</tr>
</thead>
<tbody>
<?php while ($r = $q->fetch()): ?>
<tr>
<td><?php echo htmlspecialchars($r['school'])?></td>
</tr>
<?php endwhile; ?>
</section>
<footer id="the_footer">
City CV Tool 2014
</footer>
</div>
</body>
</html>
The problem is that no matter how I change it, it still gives me an error. The error is at these specific lines:
while ($r = $q->fetch()) {
echo sprintf('%$department', $r['school']);
}
The error might be just something missing or something extra that I put without realizing it. I know the code is about a very specific case, but still any help is appreciated.
You never close the following string variable :
$sql = 'SELECT *
FROM education
WHERE school LIKE ?;

Button doesn't appear after while cycle even though it works if i put it before cycle

I have my footer.php with admin button in it and when i include it at the end of my page the button doesn't appear.. But if i put it before this code:
<?php if ($row["rights"]=="2"):?>
<div id='cssmenu-admin'>
<ul>
<li name='admin' class='active'><a href='administration.php'><span>Admin</span></a></li>
</ul>
</div>
<?php endif; ?>
from footer.php before while cycle it works like it should.
This my footer.php file:
<div id="footer">
<hr>Copyrighted (C) 2014 by djdanas#gmail.com<br>
<?php if ($row["rights"]=="2"):?>
<div id='cssmenu-admin'>
<ul>
<li name='admin' class='active'><a href='administration.php'><span>Admin</span></a></li>
</ul>
</div>
<?php endif; ?>
</div>
<br><hr>
And this is my page file:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Pagrindinis</title>
<link href="CSS/stilius.css" rel="stylesheet" type="text/css"/>
<link href="CSS/menu.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php require("includes/validate.php");?>
<?php require("includes/stilius.php");?>
<?php
require("includes/connection_to_db.php");
$sql = "SELECT prekės.* , CONCAT(vartotojai.name) as v_name
FROM prekės
LEFT JOIN vartotojai
ON vartotojai.V_ID=prekės.V_ID
ORDER BY prekės.date
DESC LIMIT 8";
$result = mysql_query("$sql");
?>
<?php mysql_close(); ?>
<?php while ($row = mysql_fetch_assoc($result)) : ?>
<?php $image = '<td><img src="data:image/jpeg;base64,'.base64_encode($row['image']).'" name="pix" width="270" height="200"/></td>' ?>
<table class="two">
<th><?php echo $row['name'] ?></th>
<th>Prekės savininkas: <?php echo $row['v_name']?></th>
<th><input type="button" value="Mainyti"></th>
<tr>
<?php echo $image?>
<td><textarea disabled style="resize:none; background-color:white" name="about" rows="12" cols="65"><?php echo $row['specs']?></textarea><td>
</table>
<?php endwhile; ?>
<?php require("includes/footer.php");?>
</body>
</html>
EDIT:
Ok, i solved my problem by adding new variable
$rights = $row['rights'];
right after
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Pagrindinis</title>
<link href="CSS/stilius.css" rel="stylesheet" type="text/css"/>
<link href="CSS/menu.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php require("includes/validate.php");?>
<?php require("includes/stilius.php");?>
in my page file and changed 1 line in my footer.php file from
<?php if ($row['rights']=="2"):?>
to
<?php if ($rights="2"):?>
now it's working like a charm :)
I'll take a stab in the dark here and say that your test
if ($row["rights"]=="2")
means you are checking to see if the user logged in has the "rights" of 2?
Then when you loop through your query...
while ($row = mysql_fetch_assoc($result))
You are overwriting your $row variable. So whatever you thought was in there to begin with, isn't anymore. You should use a different variable for either your user or looping through the query.
EDIT:
It's also possible that the variable isn't in scope once you get to where you are testing it. You could try using a print_r($row) in footer.php to see what is currently inside of $row -- that should help.

Dynamically change the title of the page with 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>

Categories