Printing a Record multiple times in PHP and MySql - php

I am trying to create a webpage that does a simple query of a table and displays the table to a page, but with one complex twist that has got me confused. Here are the column names and one example record from the table separated by commas:
R_ID , B_ID , R_No , RoomName , showers , eyewashPlumbed , EyewashBottles
1 , 609 , 609 , Hazardous Waste Shed , 1 , 1 , 1
I need to print each row of this table, but also print multiple rows if either showers, eyewashPlumbed, or EyewashBottles is greater than 0. For example, I would print this row three times. If showers was 0 I would only print it two times (one for eyewashPlumbed, one for EyewashBottles, and 0 for showers). If showers was 2 I would print it 4 times, etc.
The code I'm using to print is as follows:
<?php while ($row = mysql_fetch_array($result, MYSQL_ASSOC)): ?>
<tr>
<td><?php print $row["B_ID"];?></td>
<td><?php print $row["R_No"];?></td>
<td><?php print $row["RoomName"];?></td>
<td><?php print $row["Showers"];?></td>
<td><?php print $row["eyewashPlumbed"];?></td>
<td><?php print $row["EyewashBottles"];?></td>
</tr>
<?php endwhile; ?>
The problem is that I don't know how to interrupt the while loop in order to print the same row multiple times. It goes onto the next row as it pulls from the mysql_fetch_array.

You really should switch to PDO / mysqli, but with your current code it would be something like (for showers as in your example):
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)):
$count = 2 + $row["showers"];
for ($i = 0; $i < $count)
{
?>
<tr>
<td><?php print $row["Date"];?></td>
<td><?php print $row["Inspector1"];?></td>
<td><?php print $row["Inspector2"];?></td>
<td><?php print $row["Building_Name"];?></td>
<td><?php print $row["Room"];?></td>
<td><?php print ($i + 1);?></td>
</tr>
<?php
}
endwhile;
?>
You probably want to change $row["shower_no"] to something like $i + 1 as that column does not appear in your database.

If you have a variety of rules
I would handle this problem like this:
<?php
function printRow($row=array(), $times=1) {
for($i=0; $i<$times; $i++) {
echo "
<tr>
<td>{$row["Date"]}</td>
<td>{$row["Inspector1"]}</td>
<td>{$row["Inspector2"]}</td>
<td>{$row["Building_Name"]}</td>
<td>{$row["Room"]}</td>
<td>{$row["shower_no"]}</td>
</tr>
";
}
}
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
switch(true) {
case ($row['eyewashPlumbed']>0 or $row['EyewashBottles']>0):
printRow($row, 3); // print 3 times
break;
case ($row['showers']==0): // print 2 times
printRow($row, 2);
break;
default: // default print 1 time only
printRow($row, 1);
}
}
?>

Related

PHP trying to print in 3 columns of 8 rather than 1 column of 24

I currently can print 8 records in one column, I am trying to print 16 records in 2 columns of 8 or 24 in 3 columns of 8. After several months of trying I have to admit it baffles me. Any help or guidance would be greatly appreciated. My code below gives me the first column of 8 perfectly, but after that I am stuck
$result1 = $db->prepare("SELECT * FROM table WHERE id='100' ORDER BY id ASC LIMIT 8 ");
$result1->execute();
print("");
$count = $result1->rowCount();
print("");
for($i=0; $row = $result1->fetch(); $i++) {
?>
<body topmargin="0">
<table border="0">
<tr>
<td>
<font size="5">ID:<?php echo $row['id']; ?></font><br>
<font size="5"><?php echo $row['field1']; ?></font><br>
<font size="5">Field1<?php echo $row['field2']; ?></font><br>
<font size="4">Field2<?php echo $row['field3']; ?></font><br>
<font size="3">Field3<?php echo $row['field4']; ?></font><br>
</td>
</tr>
<?php
}
?>
I would approach this by making a loop to output a table with a desired column count.
Within that you will need to iterate a number of rows, and then inside that loop, write out the table entry for each of the columns.
If your data doesn't exactly fill columns x rows then you'll get some blank items of course.
$rows = ceil($count / $columns)
for ($r = 0; $r < $rows; $r++) {
echo "<tr>";
for ($c = 0; $c < $columns; $c++) {
$value = $result1->getNext() ?? '';
echo "<td>{$value}</td>";
}
echo "</tr>";
}
The getNext() here is up to you of how best to implement. You could load all the values into an array and increment an index counter, or your $db class may give you a more helpful accessor for getting the next value.

How to get first id from the fetched rows in php mysql?

I am fetching data in php from mysql table. Let say I retrieved 15 rows containing 15 unique ids. Now I want to get the the very first fetched id from the results.
This is what I'm trying..but its giving me the last id
<?php
$results = $db->query("SELECT * FROM orders where Sales_Rep='$sales_rep'");
while($row = $results->fetch_assoc()){
?>
<tr>
<td><?php echo $row["Order_ID"] ?></td>
<td><?php echo $row["Company_Name"]?></td>
</tr>
<?php
$last_order_date= $row["Order_ID"];
echo $last_order_date;
} //end of while loop
?>
you could simply add index like this
$i = 0;
while loop
$i++;
if($i === 1)
{get ID}
//rest of your while loop
endwhile;
you can modify your sql to
SELECT * FROM orders where Sales_Rep='$sales_rep' Order By Order_ID DESC
or you use this code
<?php
$results = $db->query("SELECT * FROM orders where Sales_Rep='$sales_rep'");
$i =0;
$first_id = 0;
while($row = $results->fetch_assoc()){
if ($i===0){
$first_id = $row["Order_ID"];}
$i++;
?>
<tr>
<td><?php echo $row["Order_ID"] ?></td>
<td><?php echo $row["Company_Name"]?></td>
</tr>
<?php
$last_order_date= $row["Order_ID"];
echo $last_order_date;
} //end of while loop
?>
your first Id is in $first_id

Refer to objects within a loop in php

I would like to use a for loop to access 10 objects of the same class.
The reason is that I want to make a table of the data and I don't find it proper to write by hand all the html markup for each row (object) on the table.
My code is :
<?php
for ($i=1;$i<=10;$i++){
?>
<tr>
<td><? echo $i;?></td><td><?php echo $office1->pc;?></td>
<td><?php echo $office1->pc*$office1->pcPowerPerUnit;?></td>
<td><? echo $office1->printer;?></td>
<td><?php echo $office1->printer*$office1->printerPowerPerUnit;?></td>
<td><? echo $office1->lights;?></td>
<td><?php echo $office1->lights*$office1->lightsPowerPerUnit;?></td>
<td><? echo $office1->aircondition;?></td>
<td><?php echo $office1->aircondition*$office1->airconPowerPerUnit;?></td>
<td><? echo $office1->server;?></td>
<td><?php echo $office1->server*$office1->serverPowerPerUnit;?></td>
</tr>
<?php } ?>
What I thought that could be done is to change the references $office1->pc (for example) to $office[$i]->pc or something like that but that doesn't seem to work. I also searched for object iteration in the php manual but that wasn't helpful.
The number of objects is fixed (10) and the properties are already calculated and ready to be echoed out.
You can use a special syntax to refer to your variables like that. Ty this:
<?php echo ${'office'.$i}->pc;?>
Use variable variables:
for ($i = 1; $i <= 10; $i++) {
// ...
$officeVar = 'office' . $i;
// Now you can use $officeVar as a variable variable:
$$officeVar->pc;
// equivalent to:
$office1->pc;
// when $i == 1
// ...
}
foreach( array( $office1, $office2, $o3, $o4) as $o ) {
?>
...
... <?php echo $o->pc;?> ...
<?php
}
Extend the array as needed. Object variables hold a handle refering to the object so this is a cheap operation and not a copy.
First of all store the column output values into an array:
$columns = array($i, $office->pc, $office->pc*$office->pcPowerPerUnit, ...);
you can then output the columns independent to the values in your variables:
echo '<tr><td>', implode('</td><td>', $columns), '</td></tr>';
The only thing left is that you iterate over all those variables you have. Taken an array is much better than using $office1 to $office10:
foreach($offices as $i => $office)
{
$columns = array($i, $office->pc, $office->pc*$office->pcPowerPerUnit, ...);
echo '<tr><td>', implode('</td><td>', $columns), '</td></tr>';
}
Done. However if you don't want to change due to some reason (e.g. not changing too much at once), you can do similar:
foreach(range(1, 10) as $i)
{
$office = ${'office'.$i};
$columns = array($i, $office->pc, $office->pc*$office->pcPowerPerUnit, ...);
echo '<tr><td>', implode('</td><td>', $columns), '</td></tr>';
}

Echo current number of row

My $num_rows echos the total row count but I want the current row number.
<?php
$result = mysql_query('SELECT * FROM texts ORDER BY id desc');
while($row = mysql_fetch_array($result)){
$num_rows = mysql_num_rows($result);
?>
<tr class="alt">
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['title']; ?></td>
<td>Original</td>
<td>#English</td>
<td><?php echo $num_rows; ?></td>
</tr>
<?php
}
?>
Thank you :)
why you should not use a increment variable to count the loop turns inside while?
$tmpCount = 1;
while() {
$tmpCount ++;
}
Is this helpful to you? or are you expecting the physical row number of from database?
If you want to just number the rows returned by the query (instead of using the actual ID - $row['id'] presumably), you can just increment a number with each row:
$num_rows = 0;
while ($row = mysql_fetch_array($result)){
$num_rows++;
// ...
This works, but when sorting, the number gets locked in and doesn't return to the natural sort. The initial sort will be 1, 2, 3 but when clicking on the column to sort, whatever row is associated with the first sort will stay with it and the new sort will not have the num_rows in order!

PHP/MySQL Output Data in TD's

How would I go about imposing a restriction on the number of HTML table columns when querying the database.
For example, I have a MySQL table with the following values:
myTable:
id color
1 red
2 blue
3 green
4 pink
5 purple
And when I run my query, instead of showing all rows in traditional table rows, e.g.
<table>
<?php
while {
echo "<tr><td>$row['color']</td></tr>;
}
?>
</table>
Instead, I would like to impose something where, every three td's, a new tr is created.
For example, it would output something like this:
<table>
<tr>
<td>red</td>
<td>blue</td>
<td>green</td>
</tr> <-- Notice how after 3 columns, a new table row is created.
<tr>
<td>pink</td>
<td>purple</td>
</tr>
</table>
Any way to achieve this?
In order to achieve this, you can use a combination of a counter and a modulus (%) operator:
<table>
<?php
$count = 0;
while($row = mysql_fetch_array($results)) {
$outputTr = ($count % 3) == 0;
if($outputTr) echo '<tr>';
echo '<td>' . $row['color'] . '</td>';
if($outputTr) echo '</tr>';
$count++;
}
?>
</table>
To achive this, put in a simple counter that resets every 3 table datas.
<?php
echo "<table><tr>";
$count = 0;
foreach($data as $key => $color)
{
if($count == 3)
{
$count = 0;
echo "</tr><tr>";
}
$count++;
echo "<td>".$color."</td>";
}
echo "</tr></table>";
?>

Categories