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>';
}
Related
This is the code that I have:
<?
$i=0;
foreach ($data as $key => $value)
{
?>
<tr>
<td><?=number_format($value[budget],0)?></td>
<td><?=number_format($value[htd],0)?></td>
<td><?=number_format($value[etc],0)?></td>
<td><?
$per=number_format(($value[htd]+$value[etc])/$value[budget],2);
echo $per;
?></td>
</tr>
<?$i++;}?>
So, $per is a calculated value, and I would like to sort my table by that number. Can I get some help doing this?
You can only use the data once you have it, so:
//add what you want first
foreach($data as $key => $value){
$data[$key]['per'] = ($value['htd'] + $value['etc']) / $value['budget'];
}
//then sort
usort($data, function($a, $b){
return $a['per'] == $b['per'] ? 0 : ($a['per'] > $b['per'] ? 1 : -1 );
});
//then display the data
foreach($data as $key => $value){
?>
<tr>
<td><? echo number_format($value['budget'],0); ?></td>
<td><? echo number_format($value['htd'],0); ?></td>
<td><? echo number_format($value['etc'],0); ?></td>
<td><? echo number_format($value['per'],2); ?></td>
</tr>
<?
}
Before output table you need to sort the $data array using some of PHP sorting functions. Look at usort function. It can help you.
That loop using do while, and it is working fine but when I add another do while in to this the second do while work but first do while only show one row not all 10 row. My code is below
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<?php do { ?>
<td><?php echo $row_Recordset1['nav']; ?></td>
<?php } while ($row_Recordset1= mysql_fetch_assoc($Recordset1)); ?>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
My date should be displayed once in a row but all the other td will be took from nav;
This is what I want:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
|2014-02-25|3.1|1.2|1.5|
But I'm currently getting:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
You should look at http://php.net/mysql_fetch_assoc
It moves the internal pointer one step ahead, so each time you do mysql_fetch_assoc() you get the next value, hence only your enternal do while is executed. That is, only date from the first row is output, and all other values are output in second do while;
Try this for exercise:
$q = mysql_query("SOME MYSQL QUERY WITH MINIMUM THREE ROWS");
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
print_r($f);
First of all, please don't bounce in and out of PHP like that...
<?php
do {
echo '<tr>
<td>';
echo $row_Recordset1['date'];
echo '</td>';
do {
echo '<td>';
echo $row_Recordset1['nav'];
echo '</td>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
echo '</tr>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
?>
Where do you fetch your first $row_Recordset1? Somewhere earlier than this code? You're going to output table cells (<td>) until you run out of rows. I don't think you want that.
Like so:
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<td><?php echo $row_Recordset1['nav']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Because each time you use mysql_fetch_assoc it does the following
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
Part of the reason this doesn't work is because you are re-assigning the value of the same variable. If you don't want to lose it then you cannot do it this way. At the very least it is a bad idea if you ever intend to do anything new with the code.
Next, I really recommend you populate an array with the data first before you ever do anything with outputting it. It is a very good idea to separate logic from output.
Your code should look more like this:
<?php
//Assumes you have already connected to a mysqli resource
$conditional_data_filtered = $mysqli->real_escape_string($conditional_data);
$sql = "SELECT date, nav FROM some_table WHERE some_column = '" . $conditional_data_filtered . "'";
if ($result = $mysqli->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$data = array(); //Make sure we start with a fresh array each time.
$data['date'] = $row['date'];
//Now I think you have a bunch of data in the nav you need to loop through
$nav_filtered = $mysqli->real_escape_string($row['nav']);
$subSql = "SELECT some_data FROM navigation WHERE some_identifier = '" . $nav_filtered . "'";
if ($subResult = $mysqli->query($subSql)) {
while ($subRow = $subResult->fetch_assoc()) {
$data['nav'][] = $subRow;
}
}
$rowList[] = $data;
}
/* free result set */
$result->free();
}
foreach ($rowList as $rowData) {
echo "<tr>";
echo "<td>" . $rowData['date'] . "</td>";
foreach ($rowData['nav'] as $navData) {
echo "<td>" . $navData['some_info'] . "</td>";
}
echo "</tr>";
}
?>
Just a note: If you really don't have sub-data and just want to output the next column then you don't need a sub-loop. You just need to echo the contents of the column like you did with the first one. Then you can get rid of the sub-loops I have shown above and just put it within the first loop.
newbie PDO question...
I think (hard to tell - buried in a wrapper class) I am doing a select query using:
PDO::FETCH_ASSOC
wrapper:
return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
I am getting back just 1 record - like to display the results of just current customer....
My query is:
$results = $db->select("mytable", "id = 201"); //just 1 exact record)
then I can loop like:
foreach ($results as $result) {
....
?>
<tr>
<td><?php echo $result["First"]; ?></td>
<td><?php echo $result["Last"]; ?></td>
<td><?php echo $result["id"]; ?></td>
</tr>
This all works fine, but since I only have 1 exact CUSTOMER record - I don't need to LOOP anything.
My question is:: How do I display the columns without a loop?
The following failed:
echo $results["First"];
echo $results["First"][0];
echo $results["First"][1];
So what can I use to make it work?
Use fetch instead of fetchAll
$row = $pdostmt->fetch(PDO::FETCH_ASSOC);
You have to use the fetch function of PDO library.
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);
}
}
?>
I have some code that creates a table like this:
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td" . $i;
echo "></td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
$counter = 0;
foreach($row as $cell)
{
if($counter == 0)
{//1st column
echo "<td><strong>" .$cell. "</strong></td>";
}
elseif($counter == 8)
{//7th column
echo "<td><img src=\"http://php.alton.com/image.php/image.jpg?width=100&height=100&cropratio=1:1&image=".$cell."\" /></td>";
}
elseif($counter == 9)
{//eighth column
echo "<td><strong>" .$cell. "</strong></td>";
}
else
echo "<td>$cell</td>";
//inside your default td
$counter++;
}
echo "</tr>\n";
}
I am trying to get the MySQL result from column 0 (ID) and pass this variable into a URL parameter in the result. I want the SQL results in Column 8 to create a link that includes the ID from column 0. For example: "/details.php?ID=43" where the ID comes from the 1st column in the row. Does this make sense?
Your output code is inherently bad since it relies on the order the results are returned in from the database. This may work now, but is an incredibly fragile way of doing things. You should refer to your fields (columns) by name, not by the order they're returned in. You're also needlessly complicating your output code with that inner loop and if…else construct. Try something along these lines:
<?php while ($row = mysql_fetch_assoc($result)) : ?>
<tr>
(substitute 'col1' etc by the actual columns names)
<td><strong><?php echo $row['col1']; ?></strong></td>
<td><?php echo $row['col2']; ?></td>
…
<td>
<img src="http://php.alton.com/image.php/image.jpg?width=100&height=100&cropratio=1:1&image=<?php echo $row['image']; ?>" />
</td>
…
</tr>
<?php endwhile; ?>
I'm not quite sure about your actual question, but approaching your problem like this may answer it already.