Good afternoon all :)
I would like to display my MySQL output on a PHP page as rows rather than columns for easier mobile viewing and scrolling (so the user can just scroll down the data instead of across).
I'd read about pivots and transposing but wasn't sure what was the most appropriate way to transform the return data output on the webpage. Please can you advise on what is best to use? It looks like it's easier to do it in PHP rather than MySQL?
I'm using a standard post form, connection PDO, isset, thead, php echo td and th etc.
My current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h1>Find people</h1>
<form method="post">
<label for="people">Enter person</label>
<input type="text" id="people" name="people">
<input type="submit" name="submit" value="View Results">
</form>
<?php
//error_reporting(-1);
//ini_set('display_errors', 'On');
if (isset($_POST['submit'])) {
try {
require "./config.php";
require "./common.php";
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT *
FROM Basics
WHERE UniqueID = :people";
$people = $_POST['people'];
$statement = $connection->prepare($sql);
$statement->bindParam(':people', $people, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php
if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>
<table>
<?php echo '<table border="1">';?>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["Field 1"]); ?></td>
<td><?php echo escape($row["Field 2"]); ?></td>
<td><?php echo escape($row["Field 3"]); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<br>No results found for <?php echo escape($_POST['people']); ?>, as the data has likely not been added yet.
<?php }
} ?>
<!--
<?php if (isset($_POST['submit']) && $statement) { ?>
<?php echo escape($_POST['people']); ?> successfully found.
<?php } ?>
-->
</body>
</html>
My current output:
Current example output:
Output example I would like:
Similar to this example I found (can be in a table or not like below):
Update edit:
Looks like I just needed to use ul and li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>
I would use array_walk() to loop over the rows and within that loop, start the tr-tag, loop over the values of the current row, output them as td-elements, exit the td-loop, output the closing tr-tag and exit the tr-loop. Not that fancy solution but simple.
Looks like I just needed to use ul and li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>
Related
The thing is that I want to check if user's super variable is same as a value that I have on another variable that contains an array of values.
The problem is that the array is on 2 dimentions, so I need to loop the array before checking if it matches with the variable I am getting from the URL.
I don't want to do it with a function, but the best way of accomplishing it.
Here's the code:
<?php
$detalles = [
array("nombre"=>"Manzana", "precio"=>45.95, "color"=>"Rojo"),
array("nombre"=>"Pera", "precio"=>40.36, "color"=>"Verde"),
array("nombre"=>"Uva", "precio"=>95.21, "color"=>"Purpura"),
array("nombre"=>"Naranja", "precio"=>15.60, "color"=>"Naranja"),
array("nombre"=>"Mango", "precio"=>10.80, "color"=>"Amarillo")
];
?>
<!DOCTYPE html>
<html>
<head>
<title>Results of $_GET variable</title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div style="margin-top: 20px" class="container">
<table class="table table-striped">
<tr>
<td colspan="2">Product details</td>
</tr>
<?php foreach($detalles as $producto):
if(!isset($_GET['producto']) || $producto["nombre"] != $_GET['producto']){
header('Location: index.php');
}
if($producto["nombre"] == $_GET['producto']): ?>
<tr>
<td>Nombre:</td>
<td>{ <?php echo $producto["nombre"]; ?> }</td>
</tr>
<tr>
<td>Precio:</td>
<td>{ <?php echo $producto["precio"]; ?> }</td>
</tr>
<tr>
<td>Color:</td>
<td>{ <?php echo $producto["color"]; ?> }</td>
</tr>
<?php endif;
break;
endforeach; ?>
</table>
</div>
</body>
</html>
This is the details.php file, there's a file that is previous of this one which has a form with a get method and an action so everything works fine, my logic is what is not right.
Thank you in advance.
Blessings
You check in every loop if $_GET['producto'] is set. You have to check it once before the loop.
Don't print the details in your loop. First you have to find the product, and then show the details.
<?php
if( !isset($_GET['producto']) ) header("Location: index.php");
$found = null;
foreach($detalles as $producto){
if( $producto["nombre"] == $_GET['producto']){
$found = $producto;
break;
}
}
?>
<tr>
<td>Nombre:</td>
<td>{ <?php echo $found["nombre"]; ?> }</td>
</tr>
...
I'm trying to display an image which have been stored in MySQL, but haven't been able to get a success just yet. Apparently echoing the table header (img) gives me back something like this
In addition I would like to be able to add the image in the website itself rather than using the phpmyadmin and inserting the image there.
As of now this is the code I have for the standing.php page
<?php
require_once('database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main id="standingListMain">
<h1 id="addCategoryh1">Team Standings</h1>
<table id="standingListTable">
<tr>
<th>Team</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryID']; ?></td>
<td>
<?php echo $team['categoryName']; ?>
<?php echo $team['img']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
</main>
<!-- <footer id="standingListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer> -->
</body>
</html>
Basically, the user can add or remove a team from the team_list.php page and view it on the standings page
<?php
require_once('../Model/database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main>
<h1 id="addCategoryh1">Teams</h1>
<table id="categoryListTable">
<tr>
<th>Name</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryName']; ?></td>
<td>
<form action="delete_team.php" method="post"
id="delete_product_form">
<input type="hidden" name="team_id"
value="<?php echo $team['categoryID']; ?>">
<input id="deleteCategoryList" type="submit" value="Delete">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<h2 id="add_category_h2">Add Team</h2>
<form action="add_team.php" method="post"
id="add_category_form">
<label>Name:</label>
<input type="input" name="name">
<input id="add_category_button" type="submit" value="Add">
</form>
<br>
<p>View Team List</p>
</main>
<footer id="categoryListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer>
</body>
</html>
Code above is the team_list.php page and below is the code to connect to the database called the add_team.php
<?php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
}
?>
The image above shows the page where u can add or remove a team.
For testing purposes
First you need to know if the Image really exist. Let's assume that in your database you have an image with category Id of 1. Thus create another file, eg "image.php".
(Please ensure that this code runs correctly. I have not tested it but it should work for you).
image.php
<?php
require_once('database.php');
// Get all categories
$query = "SELECT img FROM categories where categoryID=1";
$statement = $db->prepare($query);
$statement->execute();
$num = $statement->rowCount();
if( $num ){
$teams = $statement->fetchAll();
// Ensure to specify header with content type,
// you can do header("Content-type: image/jpg"); for jpg,
// header("Content-type: image/gif"); for gif, etc.
header("Content-type: image/png");
//display the image file
print $teams['img'];
exit;
}else{
//echo no image found with that Category Id.
}
?>
Then in your "standing.php", remove this code:
<?php echo $team['img']; ?>
and replace it with:
<!– "1" is the categoryID id of the image to be displayed –>
<img src="image.php?id=1" />
I am trying to add stuff into an array after every click a user makes on a category but for some reason it keeps replacing everything in the array. I can't figure out where I am going wrong. I've tried 'googling' it and every example i find looks similar to what i have written. Please Help!
these functions are store in core.php
function getStoreBacktrace($cat) {
include("config.php");
$backtrace = array();
if ($cat != 0) {
array_push($backtrace, $cat);
}
if (count($backtrace != 0)) {
foreach($backtrace as $c){
echo getBackCatName($c);
}
}
print_r($backtrace); // Put this to see what output is
}
function getBackCatName($c) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `id`="'.$c.'"';
$r_query = mysql_query($query);
$result = mysql_fetch_array($r_query);
echo ' > '.$result['name'].'';
}
this function prints out a list of links the user can click on
function getStoreCat($cat) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `main`="'.$cat.'" ORDER BY `name` ASC';
$r_query = mysql_query($query);
echo '<ul>';
while ($result = mysql_fetch_array($r_query)) {
echo '<li>';
echo ''.$result['name'].'';
echo '</li>';
}
echo '</ul>';
}
and it gets called in store.php
<?php
include("config.php");
include("core.php");
$backtrace = array();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title><?php echo getSiteTitle().' :: '.getSiteSlogan(); ?></title>
</head>
<body>
<table width="100%">
<tr>
<td colspan="2">
<!-- Backtrace -->
Home
<?php echo getStoreBacktrace($cat, $backtrace); ?>
</td>
</tr>
<tr>
<td>
<!-- Categories -->
<table>
<tr>
<td><?php echo getStoreCat($cat); ?></td>
</tr>
</table>
</td>
<td>
<!-- Products -->
<table>
<tr>
<?php echo getStoreProducts($cat); ?>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
now everytime a user clicks on a link that is made from the function getStoreCat($cat) it refreshes the page with new links to click on and new products to show depending on what $cat they chose. i want to push the $cat to the $backtrace array.
Right here:
$backtrace = array();
You are effectively resetting the array for each call to getStoreBacktrace().
EDIT:
Thanks for fixing your question. Now it's clear that the issue is you need to make $backtrace persistent through multiple page views. Do this using sessions:
Page template
<?php
session_start(); // enable sessions
include("config.php");
include("core.php");
?>
<!DOCTYPE html>
etc...
Function definition
<?php
function getStoreBacktrace($cat) {
include_once("config.php"); // use include_once() to prevent possible errors
if (!isset($_SESSION['backtrace']))
$_SESSION['backtrace']= array();
if ($cat != 0) {
array_push($_SESSION['backtrace'], $cat);
}
...
Everytime you call getStoreBacktrace you instantiate a brand new array in $backtrace.
I'm trying to create a piece of PHP code that will create an HTML table for every array in my database table. The point of this is that a new HTML table will be created if a new array is added in the database.
This is my code as it is now:
<?php
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JOY FLOWERS</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<div id="outter">
<div id="top"></div>
<div id="menu">
<ul>
<li>Home</li>
<li>Proionta</li>
<li>Epikoinonia</li>
</ul>
</div>
<div id="body">
<div id="leftcol"></div>
<div id="midcol">
<?php
$con = mysql_connect ( "localhost", "root", "tei#123" ) or die ( "Αποτυχία σύνδεσης με τον Server<br />" );
mysql_select_db ( "proionta", $con ) or die ( "Αποτυχία σύνδεσης με την database<br />" );
$query = "SELECT * FROM proionta";
mysql_query ( "SET NAMES 'utf8';", $con );
mysql_query ( "SET CHARACTERS SET 'utf8';", $con );
$result = mysql_query ( $query, $con );
$row = mysql_fetch_array ( $result );
foreach ($row as $result);{
?>
<table>
<tr>
<th><img src="<?php echo $row["eikona"]?>" width="100%"</th>
</tr>
<td><?php echo $row["proion"]; ?></td>
</tr>
<tr>
<td><?php echo $row["timh"];?> ευρώ /τεμάχιο</td>
</tr>
</table>
<?php }?>
</div>
<div id="rightcol"></div>
</div>
</div>
</body>
</html>
I tried to use loops such as foreach and while but I failed.. considering this is my first ever PHP project I feel a bit lost in all the information I received in the last couple of days so I could really use some help on this one..
This is the foreach loop I used. I feel like $row and $result should be the other way around but this is the only way I don't get an error.. It only creates a table for the first array though.
Thanks in advance and please forgive any english mistakes
Try with something like this:
while($row = mysql_fetch_array ( $result )) {
?>
<table>
<tr>
<th><img src="<?php echo $row["eikona"]?>" width="100%"</th>
</tr>
<td><?php echo $row["proion"]; ?></td>
</tr>
<tr>
<td><?php echo $row["timh"];?> ευρώ /τεμάχιο</td>
</tr>
</table>
<?php } ?>php
I would like to ask some help and ideas on how to implement a loop inside the template. I can do foearch below but how can i include it to the template and show it in the results.
foreach($results as $row) {
$name = $row['name'];
$address = $row['address'];
}
What i want to achieve the results is something like below and how do I put the $template->publish(); in a variable so I can use it to store that data to the DB. thanks a lot.
<html>
<head>
<title>My Template Class</title>
</head>
<body>
<table><tr>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
</tr>
</table>
</body>
</html>
The template class
<?
class Template {
public $template;
function load($filepath) {
$this->template = file_get_contents($filepath);
}
function replace($var, $content) {
$this->template = str_replace("#$var#", $content, $this->template);
}
function publish() {
eval("?>".$this->template."<?");
}
}
?>
The template design.html
<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
</body>
</html>
the index.php
<?
include "template.class.php";
$template = new Template;
$template->load("design.html");
$template->replace("title", "My Template Class");
$template->replace("name", "William");
$template->replace("datetime", date("m/d/y"));
$template->publish();
?>
PHP itself is as good at templates as any other engine.
No need anything else
$pagetitle = "My Template Class";
foreach($results as $row) {
$row['date'] = date("m/d/y");
$data[] = $row;
}
$data = chunk_split($data,3);
Then in template
<html>
<head>
<title><?=$pagetitle?></title>
</head>
<body>
<table>
<?php foreach ($data as $chunk): ?>
<tr>
<?php foreach ($chunk as $row): ?>
<td>
<h3>Hello <?=$name?>!</h3>
<p>The time is: <?=$date?></p>
<p>Embedded PHP works in the template</p>
<p><b>But embed PHP in the data is a VERY BAD IDEA</b></p>
<p><?=$address?></p>
</td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
</body>
</html>
I made your example a bit more complicated yet closer to the real life.
It will print your table in the rows by 3 columns in each
Just don't re-invent the wheel, PHP works wonderfully as a templating language:
The template class
<?
class Template
{
private $template;
private $vars;
function load($filepath) {
$this->template = $filepath;
}
function replace($var, $content)
{
$this->vars[$var] = $content;
}
function publish()
{
extract($this->vars);
include($this->template);
}
}
?>
The template design.phtml
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<?php foreach($rows as $row) { extract($row); ?>
<h3>Hello <?php echo $name; ?></h3>
<p>The time is: <?php echo $datetime; ?></p>
<?php echo "<p>Embedded PHP works too!</p>"; ?>
<?php } ?>
</body>
</html>
The use is pretty much the same, just assign more than one row to make use of it:
<?
include "template.class.php";
$template = new Template;
$template->load("design.phtml");
$template->replace("title", "My Template Class");
$rows = array();
$rows[] = array(
"name" => "William",
"datetime" => date("m/d/y"),
);
$template->replace("rows", $rows);
$template->publish();
?>
Hope this is helpful.
Your PHP code:
$htmldata ="";
($results as $row) {
$name = $row['name'];
$address = $row['address'];
$htmldata .="
<tr><td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>".$name."</p>
<p>".$address." </p>
</td>
</tr>
";
}
Then in your template design.html, you will pass the $htmltable variable and embedd there:
<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
<table>
<?php echo $htmltable; ?>
</table>
</body>
</html>