PHP If statement, suitable? - php

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

Related

PHP While Loop to separate data in to columns

Hello Programing Newbie here.. Forgive me if I'm my question doesn't make sense. But, I'm attempting to Loop through a Table and display the Data in 3 Columns based on data..
There is a field "column_number" in the Table to identify the column it needs to be rendered to..
I have things working except getting the "Div's" assigned to "their" column.
right now the loop is creating a column for each. This is undesired..
See image..
Rendered Code :
I'll attach my Loop Code.
<?php
// display data retrieved if it's greater than zero
echo "<div id='colums'>";
if($num>0){
//echo "<div id='colums'>";
// loop through the records
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<div id='column{$column_number}'>";
//echo "<div id='column'>";
// display details
echo "<div class='Div'>";
echo "<div class='DivHeader' style='background-color:#{$title_bg_color}'>";
echo "<p style='color:#{$title_txt_color}' class='alignleft'>{$title}</p>";
echo "<p class='alignright'><a href='edit.php'>edit</a><a href='delete.asp'></a>";
echo "</p>";
echo "</div>";
echo "<div class='DivBody'>";
echo "Div Contents";
echo "</div>";
echo "</div>";
echo "</div>";
}
// the number of rows retrievede
$total_rows=0;
}
// Display message if no data found
else{
echo "<div class='alert'>";
echo "<strong>**** No User Data Found ****</strong>";
echo "</div>";
}
echo "</div>";
?>
I will try to add more information..
You can see in the first below screenshot I would like 3 Columns with the "widgets/DIV's" listed in each that have an associated column_number.
I named each "widgets/DIV's" accordingly the UserName, Column_Number and WidgetID so i can see if the DIV's are showing in the correct DIV/Column based on the logged in user.
I have also attached a pic of the Query and Data in the table for "usrid=3"
I have a Limit in the query because I was playing with possibly paging..
I must confess, The end result is to have the widgets draggable so the users can move them around and it will save/remember their place, column and order in the column.. The "Draggable" is currently working. I just want to get the widgets to land in their assigned column and then tackle the Draggable/Save..
Desired Result Screenshot :
Query and Data Screenshot :
Sample Desired Rendered Result :
Place the fetched results into an array then construct a foreach() loop and structure your column construct within the foreach() loop.
while($row = $result->fetch_assoc()){
$data[] = $row;
}
//Added a static array within $data for example purposes
$data = ['some info', 'somemore info', 'More info here'];//this is an array returned from your DB
if(is_array($data)){
$stmt = '';//declare an empty variable
foreach($data as $key => $value){
$stmt .= "
<div style='float:left; width: max-content; padding:20px;' id='columnTitle'>Column ".$key."
<div class=\"column".$key."\">".$value."</div>
</div>
";
}
$stmt .= "<div style='clear:both;'></div>";
}
Then use in html like:
<div>
<?=$stmt?>
</div>
or
<div>
<?php echo $stmt; ?>
</div>
output
Like an concept, i can propose you to modify the code according to this model:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10); // Assuming we have 10 records
$max_col = 3; //Maximum columns we need
$init_col = 1; //Initial col number
echo "<div class='columns'>\n";
foreach($array as $value){
if($init_col <= $max_col){
//display first and second column
echo 'col' . $init_col;
//set init value increment
$init_col++;
} else {
echo "\n"; //Echo new line since we have new column
$init_col = 1;
//display first and second column
echo 'col' . $init_col;
//set init value increment
$init_col++;
}
}
echo "\n</div>";
Output:
<div class='columns'>
col1 col2 col3
col1 col2 col3
col1 col2 col3
col1
</div>
For your code example i propose this:
$max_col = 3; //Maximum columns we need
$init_col = 1; //Initial col number
if($num>0){
echo "<div id='colums'>";
// loop through the records
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
if($init_col <= $max_col){
//display first and second column
echo "<div id='column{$init_col}'>";
// display details
echo "<div class='Div'>";
echo "<div class='DivHeader' style='background-color:#{$title_bg_color}'>";
echo "<p style='color:#{$title_txt_color}' class='alignleft'>{$title}</p>";
echo "<p class='alignright'><a href='edit.php'>edit</a><a href='delete.asp'></a>";
echo "</p>";
echo "</div>";
echo "</div>";
echo "<div class='DivBody'>";
echo "Div Contents";
echo "</div>";
echo "</div>";
//set init value increment
$init_col++;
} else {
//Echo new line since we have new column
$init_col = 1;
//display first and second column
//display first and second column
echo "<div id='column{$init_col}'>";
// display details
echo "<div class='Div'>";
echo "<div class='DivHeader' style='background-color:#{$title_bg_color}'>";
echo "<p style='color:#{$title_txt_color}' class='alignleft'>{$title}</p>";
echo "<p class='alignright'><a href='edit.php'>edit</a><a href='delete.asp'></a>";
echo "</p>";
echo "</div>";
echo "</div>";
echo "<div class='DivBody'>";
echo "Div Contents";
echo "</div>";
echo "</div>";
//set init value increment
$init_col++;
}
}
echo "</div>";
}
// Display message if no data found
else{
echo "<div class='alert'>";
echo "<strong>**** No User Data Found ****</strong>";
echo "</div>";
}
Hope it will helps

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 */}

Organise seats into tablerows in html output with PHP

I'm putting together something that's mean to allow for a user to book seats for a cinema showing. The row and seat numbers for every showing are stored in the database. I'm currently extracting them in the following method so that users can click on a seat button to select that seat for their booking:
echo "<form>";
echo "<table>";
while($row = mysqli_fetch_assoc($result)){
$rownum = $row['row'];
$seat = $row['seat'];
echo "<tr><td><button type=\"submit\" name=\"seatsel\" value=\"$rownum$seat\">$rownum$seat</button></td></tr>";
}
echo "</table>";
Right now this just outputs html showing all of the buttons as a single row in the table. I'd like the output to show seating across a single table row for every one of the table rows in the cinema screen. I'm not sure how to do this exactly given that each row is of differing lengths. E.g row A has twelve seats while row C has eight.
What would be the best way of accomplishing this?
You could easily update your code so that you will get a new table row every time the mysql row has another value. One thing to note is that you might want to add (depending on whether you're already sorting your results) the following ORDER BY row,seat.
echo "<form>";
echo "<table>";
echo "<tr>";
while($row = mysqli_fetch_assoc($result)){
if (!isset($oldrownumber)) $oldrownumber = $row['row'];
else if ($oldrownumber != $row['row']) {
echo "</tr><tr>";
$oldrownumber = $row['row'];
}
$rownum = $row['row'];
$seat = $row['seat'];
echo "<td><button type=\"submit\" name=\"seatsel\" value=\"$rownum$seat\">$rownum$seat</button></td>";
}
echo "</tr>";
echo "</table>";

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>";
}

PHP: html table layout with data coming from query

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.

Categories