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
Related
I try to build a Notification Popup I have for this a script what seems to work
but when I add a code I am = getting the numbers 1 2 3 4 from the 4 records from this user-id
I would like to see only the total number (4)
<?php
$q=mysqli_query($conn,"select * from notice where user='".$_SESSION['user']."'");
$rr=mysqli_num_rows($q);
if(!$rr)
{
echo "<h2 style='color:red'>No any notice for You !!!</h2>";
}
else
{
?>
<?php
$i=1;
while($row=mysqli_fetch_assoc($q))
{
echo "<Tr>";
echo "<td>".$i."</td>";
echo "</Tr>";
$i++;
}
?>
</table>
<?php }?>
simply add the echo out of your loop
$i=1;
while($row=mysqli_fetch_assoc($q))
{
$i++;
}
echo "<Tr>";
echo "<td>".$i."</td>";
echo "</Tr>";
Just output the $rr variable, it contains the number of rows.
mysqli_num_rows
UPDATE, example added based on your code:
<?php
$q=mysqli_query($conn,"select * from notice where user='".$_SESSION['user']."'");
$rr=mysqli_num_rows($q);
if(!$rr)
{
echo "<h2 style='color:red'>No any notice for You !!!</h2>";
}
else
{
echo "<h2 style='color:green'>Total Notice for you: $rr</h2>";
}
?>
Use MySQL's COUNT function..
assuming your user table has a column named id.. try
$q=mysqli_query($conn,"select COUNT(`id`) as USERS from notice where....
Doing this will result in 1 result, so remove your while and just do..
$row=mysqli_fetch_assoc($q);
echo $row['USERS'];
I have a database, i need to extract from them four record at a time.
To extract all the records i use this query:
SELECT image FROM song ORDER BY date DESC
but i need to process 4 record at a time, because in HTML i close a row every 4 images.
echo"<div class='row'>";
while ($dati=mysqli_fetch_assoc($result))
{
echo"<a href='song.php'>";
echo"<div class='col-md-3'>";
echo"<img class='img-responsive' src='".$dati['immagine']."'><br>";
echo"</div>";
echo"</a>";
}
echo "</div><br>";
I need to re-execute the command above every 4 image record as long as there are records not processed in the database.
LIMIT 4 but I would recommand you to query the record once and to add a counter in your loop to know when you have a new row
Use Module of 4 and display your format
<?php
$counter=0;
$str="";
while ($dati=mysqli_fetch_assoc($result))
{
if($counter%4==0)
{
$str="<div class='row'>";
}
$str.="<a href='song.php'>";
$str.="<div class='col-md-3'>";
$str.="<img class='img-responsive' src='".$dati['immagine']."'><br>";
$str.="</div>";
$str.="</a>";
if($counter%4==0)
{
$str.="</div><br>";
}
$counter++;
}
echo $str;
?>
or if you dont want store into string directly print like this
<?php
$counter=0;
while ($dati=mysqli_fetch_assoc($result))
{
if($counter%4==0)
{
echo "<div class='row'>";
}
echo "<a href='song.php'>";
echo "<div class='col-md-3'>";
echo "<img class='img-responsive' src='".$dati['immagine']."'><br>";
echo "</div>";
echo "</a>";
if($counter%4==0)
{
echo "</div><br>";
}
$counter++;
}
?>
Use this query
SELECT image FROM song ORDER BY date DESC limit 4
This will display four images in every row in your html using bootstrap after executing SELECT image FROM song ORDER BY date DESC .
$num_rows = mysqli_num_rows($result);
for ($j = 0; $j < $num_rows; ++$j)
$dati[$j] = mysqli_fetch_assoc($result); //$dati is now a multidimensional array with an indexed array of rows, each containing an associative array of the columns
// You could alternatively use a for loop
// for($i=0; $i<$num_rows; $i++) insert while loop
$i=0;
while($i<$num_rows){ // start the loop to insert images in every row, 4 images per row
echo"<div class='row'>";
echo"<a href='song.php'>";
echo"<div class='col-md-3'>";
if($i<num_rows) // this prevents excessive rows from being displayed after $i reaches the number of rows
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>"; //post-increment $i
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
if($i<num_rows)
echo"<img class='img-responsive' src='".$dati[$i++]['immagine']."'><br>";
echo"</div>";
echo"</a>";
echo "</div><br>"
}
The code I am posting below, iterates through a result set and prints elements (paths to images on database) so that images display in order. Only 3 images per row. I want to be able to have the same concept (i.e. 3 images or cells per row) but I want to have another div underneath it to have the word delete photo.
$n = 3;
echo "<table style='margin-right: 100px;'>";
echo "<tr>";
for($i=1; $i<=count($gallery);$i++){
$temp = array();
$temp = $gallery[$i-1];
echo "<td><div id='gallery_pic'><img id='single_pic' src='". $temp->path . "' /></div></td>";
if($i % $n ==0){
echo "</tr><tr>";
}
}
echo '</tr>';
echo '</table>';
echo "</table>";
The idea is that owner of profile should be able to delete photo by clicking it. I will handle that I am just not sure how to handle printing the table with same order by adding another row per row with delete word.
Simple. Add a new div right after div#gallery_pic and give it a width of 100%, this will force it to be below the image...
echo "<table style='margin-right: 100px;'>";
echo "<tr>";
for($i=1; $i<=count($gallery);$i++){
$temp = array();
$temp = $gallery[$i-1];
echo "<td><div id='gallery_pic'><img id='single_pic' src='". $temp->path . "' /></div><div class='delete_wrap'><a href='?delete_id=" . {image_id} . " style='width:100%'>Delete</a></div></td>";
if($i % $n ==0){
echo "</tr><tr>";
}
}
echo '</tr>';
echo '</table>';
echo "</table>";
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>';
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>";
}