PHP: html table layout with data coming from query - php

I'm trying to fix the layout of the data coming from the database in this way:
The query is returning names of games and the points awarded for each game.
The layout I need is like that:
in one row the name of the game and in a row below its points, two columns with this and then carriage break until all results are displayed.
Please see this image, it'll show some light:
http://217.116.9.130/wordpress/HTMLtableFROMquery.gif
What I have done by far is the following code, but I cannot display the layout needed.
![<?php
echo "<table border=1><tr>";
$count=0;
$sql2 = "select * from games";
$res2= $db_class->select($sql2);
if (mysql_num_rows($res2)>0) {
while($row2 = $db_class->get_row($res2)){
$gname = $row2['gamename'];
$gpoints = $row2['gamepoints'];
$count++;
echo"<td>".$gname."</td>";
if($count % 2 != 0)
{
echo "</tr><tr>";
echo"<td>".$gpoints."</td>";
}
}
}
echo "</tr></table>";
?>

What about some divs?
<?php
echo "<table border=1><tr>";
$count=0;
$sql2 = "select * from games";
$res2= $db_class->select($sql2);
if (mysql_num_rows($res2)>0) {
while($row2 = $db_class->get_row($res2)){
$gname = $row2['gamename'];
$gpoints = $row2['gamepoints'];
$count++;
echo"<td>
<div class=\"gname\">".$gname."</div>
<div class=\"gpoints\">".$gpoints."</div>
</td>";
if($count % 2 != 0)
{
echo "</tr><tr>";
}
}
}
echo "</tr></table>";
?>

You may want to create a table for each set of name-score, and then style it after your needs.
You can use the border property in CSS to style your table, and also table:nth-child(2n){ clear: left; to have only two tables on each row.
I believe this method is more flexible, as CSS gives endless possibilities for styling an element.

Related

How could you use PHP and a SQL database to change HTML <h> content?

I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}

Adding PHP table to mySQL files

hey guys this maybe a stupid question for you but I have a database containing footballers names (please see screen shot) What i need to do is display maybe 5 names side by side and then 5 below, if that make sense. is there an easy way to do this?
the code i currently have after the established connect is
$sql = "SELECT ID, NAME FROM players";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// Outputting HTML and the data from the DB. Change to $row['the name of the field you want']
echo "<div class='caption'><h3><img src='http://placehold.it/180x180' alt=''>" . $row['NAME'] . "</h3><p>";
}
} else {
echo "No players to show";
}
$conn->close();
?>
is it CSS i should be focusing on to make this look the way i want it?
sorry i am a new at this and cant get my head around it lol
try this:
I have added a counter called i which will change the div after it has listed 5 names. Then I have styled the div to 50% width and float to left which allows 2 div side by side.
<style>
.caption
{
width:50%;
float:left;
}
<?php
$sql = "SELECT ID, NAME FROM players";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<div class='caption'>";
while($row = $result->fetch_assoc()) {
$i = 0;
if($i>=4)
{
$i = 0;
echo "</div><div class='caption'>";
// Outputting HTML and the data from the DB. Change to $row['the name of the field you want']
<h3><img src='http://placehold.it/180x180' alt=''><h3>" . $row['NAME'] . "<h3>";
}
} else {
echo "No players to show";
}
$conn->close();
?>
</div>
yes, you are doing it right way. You just need to do some css. You can take some help form here :- https://designshack.net/articles/css/5-simple-and-practical-css-list-styles-you-can-copy-and-paste/

PHP If statement, suitable?

I'm working on a small university assignment to build a simple e-commerce engine using PHP for a website.
I currently have the following script setup to display products within a category, all of which are retrieved from a MySQL database.
http://example.com/category.php?id=2
The problem I am currently having is that for each product displayed the script is simply echoing each one side by side into a new table entry. This is causing them to go across the page rather than vertically.
What would be the best way to alter this code to have for example a maximum of three products per row? An If loop or something along those lines? Would appreciate the support!
<?php
//Create Session
session_start();
//Connect to database
include "conn.php";
//Retrieve Header
include "header.php";
//Get Category ID
if (isset($_GET['id'])){
$CategoryID = $_GET['id'];
//QUERY collects product name, and product ID.
$q="SELECT ProductID, ProductName, Price,img FROM Products WHERE CategoryID=$CategoryID";
//QUERY collects Product Category descriptions
$d="SELECT `Desc` FROM ProductCategories WHERE CategoryID=$CategoryID";
//retrive and execute SQL query results and save into a variable
$result = mysqli_query($_SESSION['conn'],$q);
$result2 = mysqli_query($_SESSION['conn'],$d) or die(mysql_error());
//Retrieve Product Category Description
echo "<div>";
while ($myResult = mysqli_fetch_row($result2)){ //Create an array
echo "<p>".$myResult[0]."</p>";
}
echo "</div>";
//Retrieve Products in category
echo "<div align='center'><table border='1px' bordercolor='#000000' width='200px'><tr>"; //Define table, row and div containing each product
while ($row = mysqli_fetch_row($result)){ //Create an array
echo "<td>"; //Create table cell
echo "<p><img src=".$row[3]."></p>"; //product image small (250x250 Pixels)
echo "<p align='center'><a href='product.php?id=".$row[0]."'>".$row[1]." </a></p>"; //Product ID Link and Name
echo "<p align='center'>£ ".$row[2]."</p>";
echo "</td>"; //Close table cell
}
echo "</tr></table></div>";//Close table, div and row
mysqli_free_result($result);
}
// Retireve Footer
include "footer.php";
?>
I am new when it comes to programming of any kind, so would appreciate patience/any support you could give me. Also I am aware of the SQL injection problem and will fix this at a later date.
Well you would keep track of your while iterations with a counter then everytime you hit $counter%3 === 0 (replace 3 with whatever you want per row) you would close the tr and start a new one:
$counter = 0;
$perRow = 3;
while ($row = mysqli_fetch_row($result)){ //Create an array
if($counter === 0) {
echo '<tr>';
} else if ($counter%$perRow === 0 ) {
echo '</tr><tr>';
}
echo "<td>"; //Create table cell
echo "<p><img src=".$row[3]."></p>"; //product image small (250x250 Pixels)
echo "<p align='center'><a href='product.php?id=".$row[0]."'>".$row[1]." </a></p>"; //Product ID Link and Name
echo "<p align='center'>£ ".$row[2]."</p>";
echo "</td>";
$counter++;
}
Here you go
while ($row = mysqli_fetch_row($result)){ //Create an array
echo "<tr><td>"; //Create table cell
echo "<p><img src=".$row[3]."></p>"; //product image small (250x250 Pixels)
echo "<p align='center'><a href='product.php?id=".$row[0]."'>".$row[1]." </a></p>"; //Product ID Link and Name
echo "<p align='center'>£ ".$row[2]."</p>";
echo "</td></tr>"; //Close table cell
}
echo "</table></div>";//Close table, div and row
The TR needs to be inside the while since tr is a row
You can do it the old fashion way with tables and iteration counters. You could also use a more CSS based approach.
Loop your result set, and build the inner HTML part (rows, columns)
$rows = '';
while ($myResult = mysqli_fetch_row($result2)){ //Create an array
$rows .= '<div class="inner">'.$myResult[0].'</div>';
}
Decide on the width of the inner columns x and make them float left or right, And make the outer div width * x
<style type="text/css">
div.box {
width:900px;
}
div.inner {
float:left;
width:300px;
}
</style>
And finally echo your HTML
<div class="box"><?php echo $rows; ?></div>
What you need is to keep track of the position you're at. If you want 3 cols per row it would be something like:
$count = 1;
echo '<table>';
while ($row = mysqli_fetch_row($result)) {
$tmp = $count % 3; //get the remainder
if ($tmp==1) {
if ($count!=1) {
//not the first row so close the last one
echo "</tr>";
}
//start row
echo "<tr>";
}
//show your <td> info
$count++;
}
echo '</tr></table>';

Breaking up a long line of values in a box

The array $carry_over returns a really long list of entries, too long for my printout page. I would love to make it in such a way that after 4 entries, it breaks and goes to the next line and breaks at the next four entries until all entries are in.
How can i do this?
Thanks
echo "<table class=\"altrowstable\" bgcolor = gold >\n";
$count = 0;
echo "<tr align= \"center\">\n";
$carry_over = array();
$score_count = mysql_numrows($query8);
echo "<td>"."Failed: ";
if($score_count !== 0){
while ($row8 = mysql_fetch_assoc($query8)) {
echo "<th>".$row8['course_code']."</th>";
if ( $count == 7 ){
echo "</tr>\n";
echo "</table>";
}
}
}
Update : Now only the first 7 entries are covered inside the table tags, the subsequent ones are outside the table tags. How can i put them in the tabke tags?
Thanks
Not sure if this is what you are looking for, but you could try:
$count = 0;
echo "<tr>";
while ($row8 = mysql_fetch_assoc($query8)) {
echo "<th>" . $row8['course_code'] . "</th>";
$count++;
if(count == 4) {
echo "</tr><tr>";
$count = 0;
}
}
echo "</tr>";
It looks like you're using a table for list data. Instead of using a <table>, you should be using a <ul> with <li> for each element. This can then be styled so that each li has display: inline-block;, for example.
I cannot tell what the table looks like from the code above, but you can put an iterator in to count to four then wrap. You also may want to check out Wordwrap

SQL Image Database assembling rows into HTML cells and rows

I have a database of images which I want to output as a gallery ...
I want to display each image in its own cell <td>image1</td> and limit the number of cells to 7 per row.
<tr>
<td>image1</td><td>image2</td><td>image3</td><td>image4</td><td>image5</td><td>image6</td><td>image7</td>
</tr>
Then a new row would be created and continue to output all the images.
<tr>
<td>image8</td>
and so on ..
I know how to do a query, but I am lost as to how to assemble the rows into the format I am looking for.
Can anyone please help me it would be greatly appreciated. Thanks.
First run your query, then get the mysql_fetch_assoc in a variable. Then echo your beginning tags for the table and tr. Then create a foreach loop of the query assoc, as another variable such as row, and echo $row['image'] in a td. This will add a new td with the image for every entry in the database. Then echo your closing tags for the tr and table.
$query = mysql_query("SELECT image FROM table_name");
$query_a = mysql_fetch_assoc($query);
echo "<table><tr>"
foreach ($query_a as $row)) {
echo "
<td>" . $row['image'] . "</td>
";
}
echo "</tr></table>";
Not tested, but try something like this
<table>
<?php
// make sure there is at least 1 row first
$cnt = 0;
$while($row = mysql_fetch_assoc($query))
{
if(++$cnt == 1) {
echo '<tr>';
} elseif($cnt % 7 == 0) {
echo '</tr><tr>';
}
// show images in <td>'s
echo "<td>" . $row['image']. "</td>";
}
echo '</tr>';
?>
</table>
Keep it simple:
Query the database to get the desired information, loop through the results, construct a new row come each new loop.
$sql = "Select * from table";
mysql_query($sql) or die(mysql_error());
if(mysql_num_rows !=0)
{
// Found at least one record, create table
echo "<table>";
echo "<tr>";
while($row = mysql_fetch_assoc($sql)
{
$cell_count = 0;
// Create a new row for each record found
echo "<td>" . $row['image_column']. "</td>";
$cell_count++;
if($cell_count == 7)
{
echo "</tr>";
echo "<tr>";
$cell_count = 0;
}
}
// Close the table
echo "</tr>";
echo "</table>";
}

Categories