Using PHP foreach to get mysql table data - php

ive got 1 database table contains row:
TABLE FROM reservations:
attandee01
attandee02
attandee03
attandee04
attandee05
attandee06
PHP CODE:
$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
echo '<td>' . $r['attandee1'] . '</td>';
echo '<td>' . $r['attandee2'] . '</td>'
echo '<td>' . $r['attandee3'] . '</td>'
endwhile;
or is there any simple way using foreach to echo attandee1 - attandee10?

$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
foreach($r as $value) {
echo '<td>' . $value . '</td>';
}
endwhile;
Should echo each column value per table row.
EDIT: If you only want the attendees:
$q = $db->query("SELECT * FROM bs_events
LEFT JOIN bs_reservations ON bs_reservations.id_event = bs_events.id");
while($r = $q->fetch_array(MYSQLI_ASSOC)):
for($i = 1; $i < 11 $i++) {
echo '<td>' . $r['attendee'.$i] . '</td>';
}
endwhile;

you can use foreach, of course, as $r is a regular array and can be iterated using foreach() operator. Did you try it?
However, looking at the field names, I suspect serious design flaw in your data structure.
It seems attandees should be stored in another table.
You may also consider using templates. Printing data directly from the database loop is very bad practice. You have to get all your data first and only then start printing it out.

Well yes:
for($i=1; $i<11; ++$i) {
echo "<td>".$r["attandee".$i]. "</td>";
}
But that is columns, what you want is the row based solution for that I'd use something like:
for($r=$q->fetch_assoc(); !is_null($r); $r= $q->fetch_assoc()) {
echo "<td>".array_pop($r)."</td>"; // output the only element in the array?
}
$q->free(); // don't forget to free the memory of the result set!

don't know if i understood your question... is this what you're looking for:
while($row = $q->fetch_array(MYSQLI_ASSOC)):
foreach($row as $field){
echo '<td>' . $field . '</td>';
}
endwhile;

Not really sure if this is what you are looking for, but give it a shot:
while($r = $q->fetch_array(MYSQLI_ASSOC)) {
foreach($r as $value) {
echo '<td>' . $value . '</td>';
}
}

As example you can use alternate syntax.
<table>
<?php foreach ($mysqli->query($sql) as $row ): ?>
<tr><td><?php echo $row['row_name1']; ?></td><td><?php echo $row['row_name2']; ?></td></tr>
<?php endforeach; ?>
</table>

Related

SQL Select producing slightly different results in phpAdmin vs. phpHTML

I consistently miss the first row result, which is more noticeable when there is only one row result.
I have a problem with my PDO commands. Any suggestions for how to correct please? If I remove the $pod->prepare nothing works. Not sure what to do?
<?php
$sql = "SELECT * FROM Order_Items
JOIN Parts ON Parts.id = Order_Items.part_id
WHERE Order_Items.orders_id = $id
AND qty <> 0
ORDER BY Parts.id";
$q = $pdo->prepare($sql);
$q->execute(array());
$row = $q->fetch(PDO::FETCH_ASSOC); // Roy says this is not needed
while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>' . $row['part_num'] . '</td>';
echo '<td>' . $row['part_desc'] . '</td>';
echo '<td>' . $row['qty'] . '</td>';
}
Database::disconnect();
?>
You are duplicating $row = $q->fetch(PDO::FETCH_ASSOC);.When you asing $q to $row, $q->fetch is cleared (with no data) so in the IF sentence you have no rows to fetch in $q.
You have to remove $row = $q->fetch(PDO::FETCH_ASSOC); and just use it in the IF.
Also try to do a fetchAll() to $q.
$result = $query -> fetchAll();
foreach( $result as $row ) {
/*CODE*/
}
You are not getting an SQL error. This has nothing to do with the value of the line_item_id database column.
You are getting a PHP error. The variable $line_item_id is undefined.

MySQL row being outputted twice

I need to output a name from the last added row of my table, and it works sort of, it outputs the correct data twice. So instead of name1 it gives me name1name1. I'm still a novice with PHP but i think there is a double loop somewhere in this piece of code which is giving me a hard time, but i'm still unable to locate where that is..
If someone can give me a pointer that would be greatly appreciated.
<?php $query="SELECT question FROM poll ORDER BY id DESC LIMIT 1";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
} ?>
By default, mysql_fetch_array() returns values both as associative and as enumerated (MYSQL_BOTH); specify either one or the other
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
EDIT
But the mysql extension is old and deprecated, and you really should be switching to mysqli or pdo with prepared statements and bind variables. If you're just learning, then it's best to learn the right methods with the right extensions from the start
No need of the while. You are fetching a single row. And use mysql_fetch_assoc for associative array
$row = mysql_fetch_assoc($results);
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
I would use mysql_fetch_assoc. Because this will only fetch the results as an associative array.
$query="SELECT question FROM poll ORDER BY id DESC LIMIT 1";
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}

Can I display query results without naming columns?

Is there a php or html code to dynamically generate a table.
query :
"SELECT * FROM table1;
Can I display this grid of info without any specifics.
IF there are 4 rows and 4 columns I want the table to be that size; if 5x5 than that.
It seems like this should be possible, but all code I can find wants me to specify names or columns.
Yes. There are a couple different ways to do this, but for illustration I will assume that the result of your query is stored in a variable called $results, which is simply a multidimensional array that you can loop through using a double foreach to dynamically produce your table.
echo '<table>';
foreach ($results as $row) {
echo '<tr>';
foreach ($row as $col) {
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';
OR if you don't have a $results array and are instead getting query results and building the table at the same time, something like this might be more appropriate for your needs:
echo '<table>';
while ($row = mysqli_fetch_array($query)) {
echo '<tr>';
foreach ($row as $col) {
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';
echo'<table>';
while($row = mysql_fetch_array($result))
{
echo'<tr>';
echo '<td>'.$row[colname].'</td>';
echo '</tr>';
}
echo'</table>';

PHP dynamic HTML table using SQL

Background
I am using the below code to generate a HTML table based on SQL results.
Code
$stid = oci_parse($conn, "
SELECT *
FROM
(
SELECT orders.order_no, orders.porder_no, orders.date, order_totals.value
FROM orders, order_totals
WHERE orders.order_no = order_totals.order_no
AND orders.account_no = '" . $_SESSION['session_account'] . "'
ORDER BY orders.order_no DESC
)
WHERE ROWNUM <= 15
");
oci_execute($stid);
echo "<table class='table'>
<thread>
<tr>
<th>Order No</th>
<th>Purchase Order No</th>
<th>Date</th>
<th>Value</th>
</tr>
</thread>
<tbody>";
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo '<td>' . $row['0'] . '</td>';
echo "<td>" . $row['1'] . "</td>";
echo "<td>" . $row['2'] . "</td>";
echo "<td>" . $row['3'] . "</td>";
echo "</tr>";
unset($row);
}
echo "</tbody>
</table>";
Question
Is it possible to make the HTML table generation part in the code more dynamic, so that if I need to add an additional column for example I can just ammend the SQL part in the code?
I had an idea to set the column headings using AS in SQL and I can amend the SQL to use AS to show the real column headings I want for example
SELECT orders.order_no AS "Order No"
, orders.porder_no AS "Purchase Order No"
, orders.date AS "Date"
, order_totals.value AS "Total"
but what about the HTML table part, is there some method to just print all columns and rows dynamically, like maybe create a function printTable that would handle any table?
The $row var is an array so you can loop over that too. Since you want to treat your first field differently write it out before the loop and start the loop at 1.
while ($row = oci_fetch_array($stid, OCI_NUM)) {
echo "<tr>";
echo '<td>' . $row[0] . '</td>';
for ( $ii = 1; $ii < count($row); $ii++ ) {
echo "<td>" . $row[$ii] . "</td>";
}
echo "</tr>";
}
I don't know what the unset($row) was for, so I left it out.
You can use:
SELECT * FROM {TABLENAME}
Then fetch an array.
You can get data with $row['{FIELDNAME}']
You can use double loop:
$results = $PDO->fetchAll(PDO::FETCH_ASSOC); // here is all columns and rows from db query.
echo '<table><tr>';
// loop only first row to get header
foreach ($results[0] as $header => $value) {
echo "<th>{$header}</th>"
}
echo '</tr>';
// loop all rows
foreach ($results as $row) {
echo '<tr>';
// and loop any number of columns
foreach ($row as $cellName => $cell) {
// If you have only one special case, than use if statement
switch ($cellName) {
case 'order_no':
echo "<td><a href='http://example.com/getOrder?id={$cell}'>{$cell}</a></td>";
break;
default: echo "<td>{$cell}</td>";
}
}
echo '</tr>';
}
echo '</table>';

PHP: using SQL result in a loop without re-executing query

I am trying to add 3 combo boxes which all display the exact same information that comes from my MySQL db. It seems like the code I wrote makes the entire page wait until all 3 combo boxes are populated, before continuing.
<?
$query = "Select * from tblWriters order by surname";
for ($i = 1; $i <= 3; $i++) {
$result = mysql_query($query);
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] . ", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
?>
I would like to optimize this piece of code, so the query will not be executed 3 times, as I believe this is where the page slows down.
If I put
$result = mysql_query($query);
outside of the for loop, the 2nd and 3rd combo box do not populate. I tried looking into resetting the pointer of the result, but I can't seem to figure out how that works.
Also, is there a way I can reuse the while loop, so I don't have to execute it 3 times?
Can someone point me in the right direction?
I'm pretty new to PHP and trying to learn on my own. Any help would be much appreciated. Thanks!
If you move your mysql_query() out of the loop again, you can reset your mysql-result-pointer by using mysql_data_seek() at the beginning or end of your loop.
This will result in:
mysql_query($query);
for($i=1;$i<=3;$i++);
{
mysql_data_seek(0); // reset datapointer
// output querydata
}
I'm obliged however to point out that the mysql-extension is deprecated by now and you should use mysqli or pdo for new projects and code.
Cache the query result in an array, then generate your markup:
$query = "Select * from tblWriters order by surname";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[] = $row;
}
for ($i = 1; $i <= 3; $i++) {
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
foreach ($data as $row) {
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] .
", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}

Categories