Foreach php variable value create while loop
I have a table like this full of orders, each customer will have multiple orders:
Customer ponumber quantity ..
customer1 234345 56
customer2 343454 34
customer1 w34234 54
customer5 332423 54
I'm trying to loop through each DISTINCT customer and print the corresponding orders with the following code.
<?php
include("php/database_connect.php");
$query = mysql_query("SELECT DISTINCT customer FROM orders");
$customer = mysql_fetch_array($query);
foreach($customer as $customers)
{
echo ' <li><h1>'. $customers . '</h1></li>';
$result = mysql_query("SELECT * FROM orders WHERE misc='new' AND customer='$customers' ORDER BY columnpos ASC ");
while($row = mysql_fetch_array($result))
{
echo'
<li id="id_' . $row['id'] . '">
<div class="card">
<table>
<tr>
<td>' . $row['customer'] . '</td>
<tr>
<td>P/O: ' . $row['ponumber'] . '</td>
</tr>
<tr>
<td>' . $row['partnumber'] . '</td>
</tr>
<tr>
<td><b>' . $row['quantity'] . '</b> x ' . $row['foil'] . '</td>
</tr>
<tr>
<td>' . $row['daterequired'] . '</td>
</tr>
<tr>
<td>' . $row['prep'] . '</td>
</tr>
</table>
<input class="hiddenid" type="hidden" value="' . $row['id'] . '" />
<input class="hiddenquantity" type="hidden" value="' . $row['quantity'] . '" />
<input class="hiddenpartnumber" type="hidden" value="' . $row['partnumber'] . '" />
<input class="hiddenfoil" type="hidden" value=开发者_Python百科"' . $row['foil'] . '" />
</div>
</li>
';
}
}
?>
However the above code currently prints:
customer1 234345
customer1 w34234
customer1 234345
customer1 w34234
which seems odd... its not going through each customer.
any help is greatly appreciated!
Make only one DB query (better performance) but process the results before looping over them:
$result = mysql_query("SELECT * FROM orders WHERE misc='new' ORDER BY customer ASC ");
$ordersByCustomer = array(); // nested array. 1. level: customers, 2. level: orders
while(($row = mysql_fetch_assoc($result))) {
if(!array_key_exists($row['customer'], $ordersByCustomer)) {
$ordersByCustomer[$row['customer']] = array();
}
$ordersByCustomer[$row['customer']][] = $row;
}
foreach($ordersByCustomer as $customer=>$orders) {
echo ' <li><h1>'. $customer . '</h1></li>';
foreach($orders as $order) {
// rest of HTML code
}
}
I also encourage you to use a better separation of HTML and PHP, like so, using the alternative syntax for control structures:
<?php foreach($ordersByCustomer as $customer=>$orders): ?>
<li><h1><?php echo $customer; ?></h1></li>
<?php foreach($orders as $order): ?>
<li id="id_<?php echo $row['id'];?>">
<div class="card">
<table>
<tr><td><?php echo $order['customer']; ?></td></tr>
<!-- and so forth -->
<?php endforeach; ?>
<?php endforeach; ?>
Btw, you are not generating valid HTML. li
element must be contained in ul
or ol
elements.
use
while($customer = mysql_fetch_array($query){
instead of
$customer = mysql_fetch_array($query);
foreach($customer as $customers)
{
精彩评论