У меня есть PHP файл, который отображает результаты SQL-запроса в таблице. В таблице перечислены элементы в заказах клиентов. Ниже приведен пример таблицы:
select * from v_orders:
order_number location order_stage item quantity
1 Patio1 3 17 2
1 Patio1 3 35 1
1 Patio1 3 13 6
2 Patio3 1 17 4
2 Patio3 1 15 1
2 Patio3 1 16 5
Столбцы order_number, location и stage вытягиваются из одной строки в другой таблице, поэтому они всегда одинаковы. Я хочу, чтобы мой PHP-скрипт создавал новую таблицу HTML каждый раз, когда он сталкивается с новым номером заказа. order_number, location и stage будет составлять первую строку каждой таблицы, а элемент и количество будут составлять все последующие строки. Когда скрипт находит новый номер заказа, он запускает новую таблицу. Кроме того, каждая таблица будет иметь кнопку внизу, чтобы обновить заказ.
Здесь, как я хочу, чтобы последний вывод появлялся.
Order: 1 Location: Patio1 Stage: 3
Item: 17 Qty: 2
Item: 35 Qty: 1
Item: 13 Qty: 6
(button)Update Order 1
Order: 2 Location: Patio3 Stage: 1
Item: 17 Qty: 4
Item: 15 Qty: 1
Item: 16 Qty: 5
Вот PHP, который я написал. Переменная $ new_table содержит HTML для построения этих таблиц. Скрипт использует знакомый цикл while для итерации по каждой строке. Когда текущая строка имеет поле order_number, отличное от предыдущей, оно добавляет кнопку и закрывает предыдущую таблицу и добавляет и заголовки, чтобы начать новую таблицу:
<?php
include "../util.php"; //Includes the connect string $connect
$id = $_SESSION['id'];
$query = mysqli_query($connect,"SELECT * FROM v_orders WHERE waiter=$id AND order_stage <> 4 ORDER BY order_number");
//Placeholder to hold the current order in the row.
$current_order = 0;
//while loop to iterate through the query results
while($row=mysqli_fetch_array($query)){
if($row['order_number'] != $current_order){
//Add button to the previous table and close, then start a new table
$new_table .= '
<tr>
<td><button onclick="update(\'enter_order.php?order= '.$current_number.' \')">Modify Order</button></td>
</tr>
</table>
<table style="padding:20px;border:5">
<tr><th>Order Number: '.$row['order_number'].'</th><th>Location: '.$row['location'].'</th><th>Stage: '.$row['order_stage'].'</th></tr>';
//Set the placeholder variable to the current order number.
$current_number = $row['order_number'];
}
//Add item and quantity data. Note that this code runs with every iteration of $row
$new_table.='
<tr><td>'.$row['name'].'</td><td>'.$row['quantity'].'</td><td>'.$row['price'].'</td></tr>';
} //end while loop
//After the while loop, close the last table.
$new_table.= '
<tr>
<td><button onclick="update(\'enter_order.php?order='.$current_number.'\')">Modify Order</button></td>
</tr>
</table>';
//Finally, echo the new_table variable to the browser. It should be properly formed HTML.
echo $new_table; ?>
Это отлично работает. Я получаю приятную самодостаточную таблицу для каждого заказа. Кроме того, над первой таблицей помещается кнопка "изменить порядок". Как я могу это исключить? Я попытался использовать команду ltrim как таковой:
$new_table = ltrim($new_table, '<tr>
<td><button onclick="update(\'enter_order.php?order= '.$current_number.' \')">Modify Order</button></td>
</tr>);
Но команда безнадежно путалась со всеми пробелами. Когда вы видите пробел или вкладку, команда ltrim извлекала лишние символы. Я потратил часы, пытаясь удалить все пустое пространство и поместил все на одной линии. Но это заставило меня безнадежно запутаться, потому что я потерялся без какого-либо правильного углубления.
Вместо того, чтобы сражаться с командой ltrim, я хотел бы просто изменить весь алгоритм. Есть ли способ добавить правильный код в конец каждой таблицы (Move...), не вставляя его полностью в верхнюю часть цикла while?
Выше цикла вы устанавливаете значение $ current_order, но оно не используется в цикле. Это здорово. Этот код зависит от $ current_number, который не определен во время первого цикла. Ваш алгоритм не плох, ему просто нужен код, специфичный для самого первого цикла, чтобы он работал.
while($row=mysqli_fetch_array($query)){
if (!$current_number) {//first loop, $current_number doesn't exist yet
$new_table .= '
<table style="padding:20px;border:5">
<tr><th>Order Number: '.$row['order_number'].'</th><th>Location:'.$row['location'].'</th><th>Stage: '. $row['order_stage'].'</th></tr>';
}
if(($row['order_number'] != $current_number) && ($current_number)){//won't fire on the first iteration
//Add button to the previous table and close, then start a new table
$new_table .= '
<tr>
<td><button onclick="update(\'enter_order.php?order= '.$current_number.' \')">Modify Order</button></td>
</tr>
</table>
<table style="padding:20px;border:5">
<tr><th>Order Number: '.$row['order_number'].'</th><th>Location: '.$row['location'].'</th><th>Stage: '.
$row['order_stage'].'</th></tr>';
}
//Add item and quantity data. Note that this code runs with every iteration of $row
$new_table.='<tr><td>'.$row['name'].'</td><td>'.$row['quantity'].'</td><td>'.$row['price'].'</td></tr>';
//Set the placeholder variable to the current order number.
$current_number = $row['order_number'];
} //end while loop
Вот некоторые проверенные коды, которые делают то, что вы хотите.
Он использует технику "читать вперед" для строк данных. Это упрощает логику, поскольку вы делаете что-то в порядке, а не пытаетесь разобраться в том, что вы делали последним.
Этот метод заключается в том, чтобы прочитать запись перед началом обработки данных. Обработайте запись. Прочитайте следующую запись.
PHP 5.3.18 на Windows XP (XAMPP)
Комментарии пытаются объяснить, что происходит.
Пример вывода:
Order Number: 1 Location: Patio1 Stage: 3
17 2 21.00
35 1 22.22
13 6 23.00
Modify Order
Order Number: 2 Location: Patio3 Stage: 1
17 4 31.00
15 1 32.00
16 5 21.00
Modify Order
<?php
session_start();
//..
$connect = mysqli_connect('localhost', 'test', 'test', 'testmysql');
// include "../util.php"; //Includes the connect string $connect
// $id = $_SESSION['id'];
$query = mysqli_query($connect,"SELECT * FROM v_orders ORDER BY order_number");
// Although it is a little clumsy, the code for while loops
// is easier if you use the 'read ahead' technique of the row data
// this means that changes cause the current processing to stop
$row = mysqli_fetch_array($query);
//while loop to iterate through all the orders...
while(isset($row['order_number'])) {
//Set the placeholder variable to the current order number.
$current_number = $row['order_number'];
// Start a new table...
echo '<table style="padding:20px;border:5">'
.'<tr><th>Order Number: '.$row['order_number']
.'</th><th>Location: '.$row['location']
.'</th><th>Stage: '.$row['order_stage'].'</th></tr>';
// write all the table rows for the current order
while ($row['order_number'] == $current_number) {
echo '<tr><td>'.$row['item'].'</td><td>'.$row['quantity'].'</td><td>'.$row['price'].'</td></tr>';
// read next row -- may be for a different order
$row = mysqli_fetch_array($query);
}
// Add button to the current table and close.
echo '<tr><td><button onclick="update(\'enter_order.php?order= '.$current_number.' \')">Modify Order</button></td></tr></table>';
} // end of all the orders
?>
Вы должны закрыть таблицу и добавить кнопку только тогда, когда у вас уже есть контент в $ new_table.
if ($row['order_number'] != $current_number) {
if (strlen($new_table) > 0) {
$new_table .= '
<tr>
<td><button onclick="update(\'enter_order.php?order= '.$current_number.' \')">Modify Order</button></td>
</tr>
</table>';
}
$new_table .= '
<table style="padding:20px;border:5">
<tr><th>Order Number: '.$row['order_number'].'</th><th>Location: '.$row['location'].'</th><th>Stage: '.$row['order_stage'].'</th></tr>';
//Set the placeholder variable to the current order number.
$current_number = $row['order_number'];
}
while
цикла через первом ряду ,if($row['order_number'] != $current_number)
выполняется , поскольку$current_number
не определена на данном этапе. Вот почему у вас есть кнопка над первой таблицей.