PHP incomplete result table from sql query - php

I am new to web development and starting learning about CRUD.
My question is that while I successfully show the table listing 3 product on 1 row, that on the second row the product no 4 are missing and skipping to the product no 5 and keep missing every last 3 row.
function getData(){
global $connect;
$query = "SELECT id, name, category, price, image, info FROM product_data";
$results = mysqli_query($connect, $query) or die(mysql_error());
echo "<table border = 0 >";
$x=1;
echo "<tr class='homepagetable'>";
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
if($x<=3){
$x = $x + 1;
extract($row);
echo "<td class='homepagetable'>";
echo "<a href=itemdetails.php?id=$id>";
echo '<img src=img/' . $image . ' style="max-width:220px;max-height:240px;width:220px;height:240px;"></img><br/>';
echo '<div class="truncate">'. $name .'</div><br/>';
echo "</a>";
echo 'Rp.'.$price .'<br/>';
echo "</td>";
} else {
$x=1;
echo "</tr><tr>";
}
}
echo "</table>";
}
Thanks in advance!

Your problem is that you have a wrong condition here:
if($x <=3)... else{...}
Change the if/else to this:
if($x <3){$x++;}
//...do something
if($x == 3){
$x = 1;
//Close and open tr
}
And you need to close the <img> tag, and the last <tr> tag outside of the loop

Perhaps you can write it like this:
function getData()
{
global $connect;
$query = 'SELECT id, name, category, price, image, info FROM product_data';
$result = mysqli_query($connect, $query) or die(mysql_error());
echo '<table border="0">';
$x=0;
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
if($x % 3 == 0)
{
// number of articles is a multiple of 3 - so close the row
if($x) echo '</tr>'; // but only if there was at least 1 article
echo '<tr class="homepagetable">';
}
$x ++;
echo '<td class="homepagetable"><a href="itemdetails.php?id='.$row['id'].'">
<img src="img/'.$row['image'].'" style="max-width:220px;max-height:240px;width:220px;height:240px;"><br/>
<div class="truncate">'.$row['name'].'</div><br/>
</a>Rp. '.$row['price'].'<br/>
</td>';
}
if($x) echo '</tr>'; // only close the row if there was at least 1 article
echo '</table>';
}

Related

Create dynamic table in php with mysql data

I would to like to create a dynamic table that the rows and columns of the table depends on the data in mysql data. Please see below my codes.
<?php
require "connect/db.php";
$query = mysqli_query($mysqli, "SELECT COUNT(level) level, shelf_no, bin_id FROM location_bin WHERE rack_id =1 GROUP BY shelf_no");
while($res=mysqli_fetch_array($query)){
$col = $res['level']; //col
$row = $res['shelf_no']; //rows
echo "<table border='1'>";
$i = 0;
while ($i < $col){
if ($i==$col){
echo "<tr>";
}
echo "<td>".$res['bin_id']."</td>";
$i++;
}
echo "</tr>";
echo "</table>";
}
?>
What I want is to display A-1-01 up to A-1-06 in the first row then A-2-01 to A-2-03 on the second row. Note that the data is dynamic.
Can you try this code . It works. change db.php path as your system path.
require "db.php";
$query = mysqli_query($conn, 'SELECT level, shelf_no, bin_id FROM location_bin ORDER BY shelf_no asc, level asc ');
echo "<table border='1'>";
echo "<tr>";
$i=0;
while($res = mysqli_fetch_assoc($query)) {
$row=$res['shelf_no'];
if ($i < $row){
$i=$row;
echo "</tr><tr>";
}
echo "<td>".$res['bin_id']."</td>";
}
echo "</table>";
?>

how to display two records in a table row out of multiple total records in php?

I have to display the SQL records (displayed in divs) in a table in which I can display only 2 records in one row. The total number of records i.e. n are not fixed and not an array too. The number of rows will depend on the number of records available. I tried couple of ways for instance defining "define('TABLE_COLS', 2);" and using for loop inside my while loop but they didn't give me the required result. The code I am working on is as following:
echo "<table>";
$sql = "Some SQL";
$result = mysql_query($sql);
$num = mysql_numrows($result);
$i = 0;
define('TABLE_COLS', 2);
echo "<tr>";
while ($i < $num) {
// for($i=0; $i<=2; $i++){
$name = mysql_result($result,$i,"name");
$Count = mysql_result($result,$i,"count");
// echo "<tr>";
echo "<td>";
echo "<div>";
echo "<div>";
echo "$name";
echo "</div>";
echo "<div>";
echo "$Count";
echo "</div>";
echo "</div>";
echo "</td>";
// echo "</tr>";
$i++;
}
echo "</tr>";
mysql_free_result($result);
echo "</table>";
The result I am looking for is like:
Now I have to add count values of corresponding event id and display it in a result table as following. I am very new in PHP so please help me. Any comments much appreciated.
+------------+ +--------------+
| Abby Bory | | Manny Mua |
+------------+ +--------------+
| 4 | | 22 |
+------------+ +--------------+
+------------+ +--------------+
| Senyz Dory| | Kory Bua |
+------------+ +--------------+
| 8 | | 27 |
+------------+ +--------------+
You can try if this help to solve your problem. I would declare multiple variables to make things easier to manage such as changing columns per row. The given code should adapt to any number of columns per row. Let me know if this is what you need.
Also, consider using mysqli instead of mysql.
Update 1: Include sample database format to standardize the format
database.php
<?php
$db_servername = "DATABASE SERVER NAME";
$db_username = "DATABASE USERNAME";
$db_password = "DATABASE PASSWORD";
$db_database = "DATABASE TABLE";
// Create connection
$con = new mysqli($db_servername, $db_username, $db_password, $db_database);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>
Example Code
require "database.php";
global $con;
echo "<table>";
$sql = "SOME SQL";
$result = mysqli_query($con, $sql);
// define number of columns per row
$num_col = 2;
// calculate total number of row based on columns per row defined
$total_row = intVal(mysqli_num_rows($result) / $num_col);
// calculate left over result if the division result is not perfect number
$left_over = mysqli_num_rows($result) % $num_col;
$counter = 0;
while($counter < $total_row){
echo '<tr>';
for($i = 0; $i < $num_col; $i++){
$row = mysqli_fetch_array($result);
echo "<td>";
echo "<div>".$row["name"]."</div>";
echo "<div>".$row["count"]."</div>";
echo "</td>";
}
echo '</tr>';
$counter++;
}
echo "<tr>";
while($left_over > 0 ){
$row = mysqli_fetch_array($result);
echo "<td>";
echo "<div>".$row["name"]."</div>";
echo "<div>".$row["count"]."</div>";
echo "</td>";
$left_over--;
}
echo "</tr>";
echo "</table>";
This can give some ideas. definitely you must pay attention to the last record because in each iteration two records are read.
echo "<table>";
$sql = "Some SQL";
$result = mysql_query($sql);
$num = mysql_numrows($result);
$i = 0;
while ($i < $num) {
$name1 = mysql_result($result,$i,"name");
$Count1 = mysql_result($result,$i,"count");
$name2 = mysql_result($result,$i+1,"name");
$Count2 = mysql_result($result,$i+1,"count");
echo "<tr>";
echo "<td>";
echo "$name1";
echo "</td>";
echo "<td>";
echo "$name2";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "$count1";
echo "</td>";
echo "<td>";
echo "$count2";
echo "</td>";
echo "</tr>";
$i+=2;
}
mysql_free_result($result);
echo "</table>";
The simple is to do this is make it on div's with bootstrap css.
Like
foreach($row = mysqli_fetch_array($result)){
echo '<div class="col-sm-3">'.$row['name'].'<br />'.$row['count'].'</div>';
}
as you see "col-sm-3" will divide one row into four columns.
and "col-sm-6" will divide row into two columns.
col-sm-12 will be the will have one row with one column.
Hope it helps.
Then try it,
echo "<table>";
$sql = "Some SQL";
$result = mysqli_query($sql);
$count = 0;
//No of columns per row
$noColumns = 2;
while($row = mysqli_fetch_array($result)){
if( $count % $noColumns == 0){
echo '<tr>';
}
echo '<td><div>'.$row['name'].'<br />'.$row['count'].'</div></td>';
$count++;
if( $count % $noColumns == 0){
echo '</tr>';
}
}
if( $count % $noColumns != 0){
//Close the last row
$remainCols = $noColumns - ($count % $noColumns);
echo '<td colspan="'.$remainCols.'"> </td>';
echo '</tr>';
}
echo '</table>';
mysqli_free_result($result);
it is based calculation with Mod(%) operator. Hope it solves.
I have used mysqli as reference instead of mysql.
This solution solved my problem.
$result = mysql_query($sql);
$num_col = 2;
$total_row = intVal(mysql_num_rows($result) / $num_col);
$i = 0;
while($i < $total_row){
echo '<tr>';
for($i = 0; $i < $num_col; $i++){
$row = mysql_fetch_array($result);
echo "<td>";
echo "<div>".$row["name"]."</div>";
echo "<div>".$row["count"]."</div>";
echo "</td>";
}
echo '</tr>';
$i++;
}
Thanks to all who helped me.
Hi this is the simplest answer i found, i went through several ways but failed, this is the right way
<table class="table" id="table">
<?php for($loop = 0; $loop <= 7; $loop++) : ?>
<td>
<input type="checkbox" name="brand[]" value="<?php echo $loop; ?>"> Brand <?php echo $loop; ?>
</td>
<?php endfor; ?>
</table>
dont use tr and in style do something like this
#table td {
width: 50%;
float: left;
}

Printing only 3 td for row in php

I am trying to print the value from database. the database contains the image URL.
I am retrieving the image url through php and printing it.
I have written this code to do so.
code:
<?php
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT name,thumbnail,link FROM courses';
mysql_select_db($dbname);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
echo "<td><a href='".$row['link']."' title='Click to see schedule'><img src='".$row['thumbnail']."'></a></td>";
echo "</tr>";
}
mysql_close($conn);
?>
This code is retriving image URL and displaying images on table. But I want 3 images per row, now it is printing only 1 image per row.
How can i do this?
You need to change your code to only open and close the row every third image. Try this:
$i = 0;
while($row = mysql_fetch_assoc($retval))
{
if($i == 0) {
echo "<tr>";
}
echo "<td><a href='".$row['link']."' title='Click to see schedule'><img src='".$row['thumbnail']."'></a></td>";
if(++$i == 3) {
echo "</tr>";
$i = 0;
}
}
// To close any open rows at the end
if($i % 3 > 0) {
echo "</tr>";
}
$cc = 0;
//initially open table row
echo "<tr>";
while($row = mysql_fetch_assoc($retval))
{
$cc++;
echo sprintf(
'<td><img src="%s"></td>',
$row['link'],
$row['thumbnail']
);
//close tablerow and open new one every 3 rows
if($cc % 3 == 0){
echo "</tr><tr>";
}
}
//close last table row
echo "</tr>";
this code prints data in 3 columns in a row. Please try
$cols=3; $col=0;
$vars = "<table>";
$vars .= "<tr>";
while($row = mysql_fetch_assoc($retval)){
$col++;
$vars .= "<td>".$row['link']."</td>";
if($col==$cols){
$col=0;
$vars .= "</tr><tr>";
}
}
$vars = "</tr>";
$vars .= "</table>";
Hope this helps.

Displaying data horizontally using php and mysql

Hi I'm attempting to display data retrieved from a mysql table horizontally in an html table using php. The code below works well except for the fact that it leaves out the first record (starts at the second record) in my database. I'm sure it has something to do with the counter but I can't seem to figure out how to get it to stop doing this. If anyone can point out my error I'd really appreciate it!
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query)
or die(mysql_error());
$row = mysql_fetch_array($result);
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
$i = 0;
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
if ($i==0) {
echo "<tr>\n";
}
echo "\t<td align=\center\">$first_name</td>\n";
$i++;
if ($i == $items) {
echo "</tr>\n";
$i = 0;
}
}//end while loop
if ($i > 0) {
for (;$i < $items; $i++) {
echo "<td> </td>\n";
}
echo '</tr>';
}//end ($i>0) if
echo '</table>';
}else {
echo 'no records found';
}
try and remove the 1st
$row = mysql_fetch_array($result);
you are calling it twice, that's why it skips 1 row in your while loop
try this simpler.
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
echo "<tr>";
for ($i=0 ; $i <= $items ;$i++) {
echo "<td align='center'>".$first_name."</td>";
}
}//end while loop
echo "</tr>";
echo '</table>';
}else{ echo 'no records found'; }
I have run into this issue before. Try the do while loop instead. Example
do {
// code
} while($row = mysql_fetch_array($result)); //end while loop
$row = mysql_fetch_array($result);
1) remove this line of code from ur scripts
2) only use while loop code instead.

How do I display two rows from sql side-by-side using php?

My code below displays 10 entries, but it displays it in 10 rows and 1 column. I would like for it to display 10 entries, but in 2 columns and 5 rows. Can anyone help? Thanks in advance.
< ?php
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10")
or die(mysql_error());
echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No')
{
continue;
}
else{
echo '<td>';
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
echo '<tr>';
}
}
echo '</table>'
?>
<?php
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()); mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10") or die(mysql_error());
$i = 1; //The following logic only works if $i starts at '1'.
$numofcols = 2; //Represents the number of columns you want in the table.
echo '<table>'; //Open table.
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No'){
continue;
}
else{
//If it's the beginning of a row...
if( $i % $numofcols == 1 ){
echo '<tr>'; //Open row
}
//Table Cell.
echo '<td>'; //Open Cell
echo 'ID Number: '.$row['id'];
echo '<br/> <img src="'.$row['Pic'].'"> <br/>';
echo '</td>'; //Close Cell
//If we have already placed enough cells, close this row.
if( $i % $numofcols == 0) {
echo '</tr>'; //Close Row.
}
//Now that we've made a table-cell, lets increment our counter.
$i = $i + 1;
}
}
//So we make sure to close our rows if there are any orphaned cells
if( ($i % $numofcols) > 0){
echo '</tr>';
}
echo '</table>' //Close Table
?>
Please note that the mod logic will only work if the starting value of $i is '1'.
This code will create a table with 2 columns.
Not tested, but basically you can call $row = mysql_fetch_array() in the loop as well to grab another row.
while($row = mysql_fetch_array( $result ))
{
echo "<tr>";
echo "<td>";
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
echo "</td>";
$row = mysql_fetch_array( $result );
if($row)
{
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
}
else
{
// Empty cell
echo "<td> </td>";
}
echo "</tr>";
}
Use modulo for echo "< tr>"
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10")
or die(mysql_error());
$i = 0;
echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No')
{
continue;
}
else{
echo '<td>';
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
if ($i % 5)
echo '</tr>';
$i++;
}
echo '</table>'

Categories