Create multiple html tables from database table using any PHP loop - php

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

Related

Get id from URL but database results aren't shown

I use the following:
<a href="showlog.php?id=<?php echo $car['car_id']; ?>">
and I get a url that looks like this:
https://example.com/showlog.php?id=AAA1111
So now in the showlog.php file I want select from a table all the lines that have this id value saved as car_id and echo the id (primary key which is different than the car_id), the trn_date, and the kilometers, so I use the following code:
<?php
include 'main.php';
checkLoggedIn($pdo);
$id=$_GET['id'];
$stmt = $pdo->prepare('SELECT id, trn_date, kilometers FROM serv WHERE car_id = '.$id.' ');
$stmt->execute([$_SESSION['id']]);
$cars = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body class="loggedin">
<div class="content">
<h2>Ser</h2>
<div>
<table>
<?php foreach($cars as $car): ?>
<tr>
<td>
<a href="showser.php?id=<?php echo "". $car["id"]. ""; ?>" style="color:DarkCyan; text-decoration: none">
<img src="images/car_service.png" width="40" height="40"> Date: <?="". $car["trn_date"]. ""?>
</a>
</td>
<td>kilometers: <?="". $car["kilometers"]. ""?></td>
</tr>
<tr><th colspan="8"><br/><hr width="100%"></th><tr>
<?php endforeach; ?>
</table>
</div>
</div>
</body>
</html>
The page loads but I get nothing as result. What am I doing wrong? :/

Displaying MySQL output in PHP as rows rather than columns

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>

Inserting and Displaying image from MySQL

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" />

Populate HTML Table with Array and Create Links

I have a site that will have pages for various countries and regions. On a main page I'm looking to populate an HTML table that is 4 columns by 12 rows (48 results) from an array. I current have a loop working that is placing each country into it's own paragraph but I'm lost on how to place them into the table and have them setup in the 4x12 way I described above.
Here is the query:
$country_sql = "SELECT * FROM country";
$country_query = mysql_query($country_sql) or die(mysql_error());
$rsCountry = mysql_fetch_assoc($country_query);
Then within the page I have this working right now that inserts each country into a new paragraph:
<?php do {?>
<p><?php echo $rsCountry['countryname'];?></p>
<?php } while ($rsCountry = mysql_fetch_assoc($country_query)) ?>
First I need to have this place data into seperate td's instead of new paragraphs. Once I have this data in a table I then need the country names link to each countries respective page which is setup as mydomain.com/country/countryabbreviation (countryabbreviation is within the same table as countryname). Any help on this would be greatly appreciated as I'm very new to php. Thanks!
----Full Code---
<?php
///CONNECTION INFORMATION REMOVED FOR PRIVACY//////////
$country_sql = "SELECT * FROM country";
$country_query = mysql_query($country_sql) or die(mysql_error());
$rsCountry = mysql_fetch_assoc($country_query);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" content="text/html">
<title>TEST PAGE </title>
</head>
<body>
<h1>List of Countries</h1>
<?php do {?>
<p><?php echo $rsCountry['countryname'];?></a></p>
<?php } while ($rsCountry = mysql_fetch_assoc($country_query)) ?>
</body>
</html>
Outputs this:
http://postimg.org/image/f2muo627d/
This should do the trick:
<?php
// Rewrote the query to only get 48 items.
$country_sql = "SELECT * FROM country LIMIT 48";
$country_query = mysql_query($country_sql) or die(mysql_error());
// Initialize an empty array.
$rsCountry = array();
// Put all our countries in there.
while ($row = mysql_fetch_assoc($country_query)) {
$item = array();
$item['href'] = '/country/' . $row['countryabbreviation'];
$item['title'] = $row['countryname'];
$rsCountry[] = $item;
}
// Chop up our massive array in rows of 4, should give us 12 rows.
$rsCountry = array_chunk($rsCountry, 4);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" content="text/html">
<title>TEST PAGE</title>
</head>
<body>
<table>
<thead>
<tr>
<td colspan="4">
<h1>List of Countries</h1>
</td>
</tr>
</thead>
<tbody><?php
foreach ($rsCountry as $row => $countries): ?>
<tr><?php
foreach ($countries as $country): ?>
<td><?= echo $country['title'] ?></td><?php
endforeach; ?>
</tr><?php
endforeach; ?>
</tbody>
</table>
</body>
</html>
is this what you want? I didn't test if it compiles
$country_sql = "SELECT * FROM country";
$country_query = mysql_query($country_sql) or die(mysql_error());
$rsCountry = mysql_fetch_array($country_query)
echo "<table><th>";
$firstrow ="";
foreach( $rsCountry as $name => $cell ){
echo "<td>$name</td>";
$firstrow = $firstrow + "<td>$cell</td>";
}
echo "</th>";
echo "<tr>$firsrow</tr>";
while( $rsCountry = mysql_fetch_array($country_query) ){
echo "<tr>";
foreach( $rsCountry as $cell ){
echo "<td>$cell</td>";
}
echo "</tr>";
}
echo "</table>";

How to increase the pagination speed

In my project I have done a pagination using PHP, I have done it as follows:
Each buttons(NEXT PAGE and PREVIOUS PAGE) are hyperlinks which links to the same page with passing a GET variable (PAGENUMBER). For each page change, there are scripts for
connect to DB .
query for the data for the specified page.
close the
DB connection. displays the data.
The problem is that it is working slowly. Is there any alternative method for each time connect to db and query for the data and close db connection.
Also During the pagination I want to reload only the datas from DB and all other contents in page remains the same and dont want to reload. How to achieve this?
The script is given below
<?php
require_once("./include/membersite_config.php"); //include files for login system
if($fgmembersite->CheckLogin())
{
$login=true;
}
else
{
$login=false;
}
require_once("db.php");
$con=connect(); //connect to db and select the db
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<HEAD>
<TITLE> Gallery </TITLE>
<META name="generator" content="Adobe Photoshop(R) CS Web Photo Gallery">
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="images/galleryStyle.css" rel="stylesheet" type="text/css">
<link rel="STYLESHEET" type="text/css" href="style/new.css" />
</HEAD>
<body marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>
<table><tr>
<?php
//////////////////DISPLAYING IMAGE THUNBNAILS//////////////////////
$query="SELECT COUNT(*) FROM gallery ";
$res = query($query);
$raw=mysql_fetch_array($res);
$imagecount=$raw[0];
if($imagecount==0) { die ("No images found"); }
$pagecount=ceil($imagecount/15);
$page = isset($_GET['page']) ? mysql_real_escape_string($_GET['page']) : 1;
if (isset($_GET['page']))
{
if (!(ctype_digit($_GET['page']) and $_GET['page']>0 and $_GET['page']<=$pagecount))
{
die ("You are not autorised to viw this page");
}
}
$start= ($page*15)-15;
$query = "SELECT * FROM gallery ORDER BY imageid DESC LIMIT $start , 15";
$res = query($query);
$count= mysql_num_rows($res);
$index=0;
for($i=1;$i<=3;$i++)
{
?>
<TR>
<?php
for($j=1;$j<=5;$j++)
{
if(!$raw=mysql_fetch_array($res)) {break;}
$index++;
$imageid=$raw['imageid'];
$thumbpath= $raw['thumbpath'];
$largepath=$raw['largepath'];
$caption=$raw['caption'];
?>
<A name=1 href="image.php?imageid=<?php echo $imageid ?>&imageindex=<?php echo ((($page-1)*15)+$index-1) ; ?> "><IMG border=0 src="<?php echo $thumbpath; ?>" height="75" width="75" alt="<?php echo $caption ?>" title="<?php echo $caption ?>" ></A><BR>
<?php
echo "<a href='delete.php?delete=yes&imageid=".$imageid.'&page='.$page."'>Delete </a>"
echo "<a href='replace.php?update=yes&imageid=".$imageid.'&page='.$page."'>Replace </a>"
?>
</table>
</td>
<?php } ?>
</TR>
<?php
}
if ($page!=1)
{
?>
<td width=17><IMG SRC="images/previous.gif" BORDER=0></td>
<?php } ?>
<td align=middle class="pagenums"><?php echo "page ".$page." of ".$pagecount ?></td>
<?php
if ($page!=$pagecount)
{
?>
<td align=right width=17><img border=0 src="images/next.gif"></td>
<?php } ?>
</table>
</body>
</html>
There are lot much options available
go with javascript pagination
ajax pagination
try to reduce pagination code(optimized code)
You do not need to connect/close db for each page change
use the ajax script for connecting and getting database values with reloading the current page you can do it -- -- -- --- -- -- try ajax

Categories