我试图从数据库中选择 ID 最高的一行,并将其回显到表中的页面。
我可以手动运行查询并且它可以正常工作,但是当我尝试通过 PHP 动态执行查询时;这是行不通的。我的代码有什么问题吗?
<?php
$sql_query = "SELECT * FROM single_user_orders ORDER BY order_id DESC LIMIT 1";
$result = mysqli_query($dbconfig, $sql_query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
echo '<div class="row" style="margin-top: 30px;">';
echo '<div class="col-md-12">';
echo '<table class="table">';
if($count > 1) {
echo '<tr>';
echo '<th>Order ID</th>';
echo '<th>Status</th> ';
echo '<th>Order Total</th>';
echo '<th>Order Description</th>';
echo '</tr>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>'. $row['order_id'] .'</td>';
echo '<td>'. $row['status'] .'</td> ';
echo '<td>'. $row['order_total'] .'</td>';
echo '<td>'. $row['order_description'] .'</td>';
echo '</tr>';
}
}
echo '</table>';
echo '</div>';
echo '</div>';
?>
最佳答案
您正在使用 while
循环再次获取数据,因为已经使用 $row = mysqli_fetch_array($result, MYSQLI_ASSOC); 获取了数据,因此无需再次获取数据。
在开头。
尝试以下
<?php
$sql_query = "SELECT * FROM single_user_orders ORDER BY order_id DESC LIMIT 1";
$result = mysqli_query($dbconfig, $sql_query);
$row = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
echo '<div class="row" style="margin-top: 30px;">';
echo '<div class="col-md-12">';
echo '<table class="table">';
if ($count >= 1)
{
echo '<tr>';
echo '<th>Order ID</th>';
echo '<th>Status</th> ';
echo '<th>Order Total</th>';
echo '<th>Order Description</th>';
echo '</tr>';
// Removed while loop as data is already fetched
// you just need to echo the values now
echo '<tr>';
echo '<td>' . $row['order_id'] . '</td>';
echo '<td>' . $row['status'] . '</td> ';
echo '<td>' . $row['order_total'] . '</td>';
echo '<td>' . $row['order_description'] . '</td>';
echo '</tr>';
}
echo '</table>';
echo '</div>';
echo '</div>';
?>
此处不需要 while
循环,因为使用 LIMIT 1
仅重试一行。如果要检索多行,在这种情况下, while 循环将为您解决问题。
关于php - 使用 PHP 从数据库表中选择最高 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39017566/