Format PHP database data - php

What I would like to know is when I grab data from a Database how can I format it with PHP so it looks nice. All i seem to be getting is a Blank white page and when i inspect the page with google chromes inspect element it says that i've got a 500 internal error.
For example, I'm using PDO to connect to the database. Heres my code:
<?php
$hostname='localhost';
$username='root';
$password='root';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=fitness", $username, $password);
$sql = "SELECT * FROM fitness";
$fitnessResult = $dbh->query($s ql);
$fitness = $dbh->fetchObject($fitnessResult);
foreach ($fitness AS $fit) {
$fitnessArray[] = ['name' => $fit->name, 'id' => $fit->description];
}
$dbh = null;
}
catch (PDOexception $e) {
echo "Error is: " . $e-> etmessage();
}
and here is my html im using the twitter bootstrap framework.
<?php
include'inc/connect.inc.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fitness</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap- theme.min.css">
<link rel="stylesheet" href="css/style.css" />
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-4">
<?php foreach ($fitnessArray AS $fitness) { echo '<h2>'. $fitness['name'] .'</h2>'; echo '<p>' . $fitness['description'] . '</p>';} ?>
</div>
<div class="col-xs-8">
<p>Dummy Text</p>
</div>
</div>
</div>
</body>
</html>
So how would I put the name into a H1 tag and the description into P tag.
Thanks

You might want to try something like the following which keeps the objects and fetchs all in an arrary
$fitnessResult = $dbh->query($sql);
$fitnessArray = $fitnessResult->fetchAll(PDO::FETCH_OBJ);
then in your html
<?php foreach ($fitnessArray AS $fitness): ?>
<h2><?=$fitness->name ?></h2>
<p><?=$fitness->description ?></p>
<?php endforeach; ?>
see official docs for fetchAll()

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 ?;

working control flow if the page has 2 html tags

regarding working control flow if the page has 2 html tags
<html>
.....
</html>
<html>
.....
</html>
WHICH WOULD BE EXECUTED BOTH OR THE ONLY FIRST ONE....
I am working on a cs50 project in which when i call
<?php
dump($_SERVER);
render("login_form.php", ["title" => "Log In"]);
?>
only dumps get executed whereas when
<?php
render("login_form.php", ["title" => "Log In"]);
dump($_SERVER);
?>
both gets executed
the details of dump and render function are..
function render($template, $values = [])
{
// if template exists, render it
if (file_exists("../templates/$template"))
{
// extract variables into local scope
extract($values);
// render header
require("../templates/header.php");
// render template
require("../templates/$template");
// render footer
require("../templates/footer.php");
}
// else err
else
{
trigger_error("Invalid template: $template", E_USER_ERROR);
}
}
function dump
function dump($variable)
{
require("../templates/dump.php");
exit;
}
the templates file are
dump.php
<!DOCTYPE html>
<html>
<head>
<title>dump</title>
</head>
similar are header.php
<!DOCTYPE html>
<head>
<link href="/css/bootstrap.min.css" rel="stylesheet"/>
<link href="/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="/css/styles.css" rel="stylesheet"/>
<?php if (isset($title)): ?>
<title>Mobi3: <?= htmlspecialchars($title) ?></title>
<?php else: ?>
<title>Mobi3</title>
<?php endif ?>
<script src="/js/jquery-1.10.2.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/scripts.js"></script>
</head>
<body>
<div class="container">
<div id="top">
<img alt="C$50 Finance" src="/img/logo.gif"/>
</div>
<div id="middle">
<body>
<pre><?php print_r($variable); ?></pre>
</body>
footer.php
<div id="bottom">
Copyright © M3shop
</div>
</div>
</body>
If the answer is "having two sets of html tags" you are asking the wrong question. Regardless on which one is shown (which can also vary from browser to browser).

Zend Framework AjaxLink Complete Failure

Having a strange zend framework issue. Although it's most likely something simple, I've been unable to resolve it so far. I have scraped the bottom of stackOverflow and several other community sites, as well as the zend documentation.
Any ajaxLink that I include in my layout refuses to function. They are classed properly, with hash placeholder in href attribute, but the javascript to activate the link is not being included in the page .
echo $this->jQuery; statement in layout is also failing. Might be the cause of ajaxLink failure. I have verified that I am properly adding the jQuery view helper in my bootstrap. Have tried using both ZendX_JQuery::enableView($view); and $view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper"); methods.
Thanks in advance
Excerpts from the relevant files follow:
bootstrap.php:
protected function _initViewHelpers()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$view->doctype('HTML4_STRICT');
$view->headMeta()->appendHttpEquiv('Content-type', 'text/html;charset=utf-8')
->appendName('description', 'Business Club');
$view->headTitle()->setSeparator(' - ');
$view->headTitle('SOU Business Club');
$view->setHelperPath(APPLICATION_PATH.'/views/helpers', '');
ZendX_JQuery::enableView($view);
}
dashboardLayout.phtml:
<?php echo $this->doctype();?>
<html>
<head>
<?php echo $this->headTitle();?>
<?php echo $this->headMeta();?>
<?php
echo $this->headLink()->prependStylesheet($this->baseUrl().'/css/dashboardStyle.css');
echo $this->headLink()->prependStylesheet($this->baseUrl().'/js/jquery/css/smoothness/jquery-ui-1.8.11.custom.css');
?>
<?php
echo $this->headScript()->appendFile($this->baseUrl().'/js/paginator.js');
echo $this->jQuery();
?>
</head>
<body id="body">
<div id="wrapper">
<div><?php include "dashboardHeader.phtml"; ?></div>
<div id="bar">
Dashboard Home|
<?php
echo $this->ajaxLink('Club Roster | ',
'user/index',
array('update' => '#content',
'method' => 'post'),
array('format' => 'html')
);
?>
Google Docs|
Book Sale Management|
</div>
<div id="content" align="center">
<?php
echo $this->layout()->content;
?>
</div>
<div id="statusBar">
<?php
$userData = Zend_Registry::get('userData');
$name = $userData->name;
$role = $userData->role;
$status = 'Logged in as: '.' Name: '.$name.' Role: '.$role;
echo $status;
?>
<br />
Logout
</div>
<div><?php include "dashboardFooter.phtml"; ?></div>
</div>
</body>
</html>
HTML <head> output:
<head>
<title>SOU Business Club - Member Dashboard</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8" >
<meta name="description" content="Business Club" >
<link href="/css/dashboardStyle.css" media="screen" rel="stylesheet" type="text/css" >
<link href="/js/jquery/css/smoothness/jquery-ui-1.8.11.custom.css" media="screen" rel="stylesheet" type="text/css" >
<link href="/css/dashboardStyle.css" media="screen" rel="stylesheet" type="text/css" >
<script type="text/javascript" src="/js/paginator.js"></script>
</head>
In your bootstrap you need to specify where jQuery is, either on your local machine or a CDN. Locally you use:
$view->jQuery()->setLocalPath(PATH);
Or you could use a CDN such as Google's: http://code.google.com/apis/libraries/devguide.html#jquery

Categories