【发布时间】:2018-12-15 14:37:33
【问题描述】:
我的目标是显示一个事务中的mysql数据,以便在不同的时间在不同的页面上查看。(事务后需要从该表中删除mysql数据以清空购物车)所以,我尝试了将 mysql 结果存储在变量中,然后对其数据进行编码并将其插入到我的 Orders 表中的 blob 格式列中。然后,我将带有 blob 值的表单输入添加到我的订单页面(用于查看先前交易的页面)。它显示表格和一行结果。 while 循环似乎没有将获取的结果的每次迭代存储到表中,因此我的订单页面上的输出只有一个行项目,而不是应有的多个行项目。谁能帮助我了解如何修复循环以便正确存储数据?
我的 while 循环并尝试将其连接回一个字符串以用作我的订单页面上的 html 表:
...
$loop= "";
while($row = $result->fetch_assoc()) {
$loop .= "<tr><td>$row[product_id]</td>
<td>$row[price]</td>
<td>$row[quantity]</td></tr>";
}
$products= "<table><tr><th>Product</th>
<th>Price</th>
<th>Quantity</th>";
$end = "</table>";
$products= $products.$loop.$end;
$products=base64_encode(serialize($products));
$sql = "INSERT INTO orders (date,username,response,products)
VALUES ('$time', '$username', '$serial','$products')";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
我的订单页面:
echo "<table id= 'orders' style='text-align: center'>
<tr><th> date </th>
<th> username </th>
<th> address </th>
<th> product total </th>
<th> shipping total </th>
<th> reference # </th>
<th> products </th>
<th> packaging </th></tr>";
$sql = "SELECT * FROM orders";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = $row['response'];
echo "<tr> <td> $row[date]</td>
<td> $row[username]</td>
<td> $row[address]</td>
<td> $row[prodtotal]</td>
<td> shipping total </td>
<td> reference #</td>
<td> <form action=
'http://localhost/WIP/secure_login/cart/Backend/orderview.php' method='POST'>
<input type='hidden' name='products' value='$row[products]'>
<input type= 'submit' value='Products'></form></td>
<td> <form action=
'http://localhost/WIP/secure_login/cart/Backend/packageview.php'
method='POST'>
<input type='hidden' name='pack' value='$row[response]'>
<input type= 'submit' value='Packaging'></form></td></tr>";
}}
【问题讨论】:
-
$result->fetch_assoc()是您第二次使用该结果集吗?然后检查this。但一般来说,以这种方式存储数据并不是一个好主意。如果要存储购物车历史记录,请将其存储在购物车历史记录表中! (例如带有product_id、price、quantity和orders表的主键的表)。想象一下,你决定例如将price*quantity显示为历史记录中的第 4 列。或者,如果您想将数据用于显示表格以外的任何其他用途,例如每月购物车产品数量的报告。 -
非常好的建议。谢谢你。我没有想到这一点。我被冲昏了头脑,没有考虑清楚。我想我只是因为发现您可以保存 HTML 代码并通过单击按钮轻松显示它而感到兴奋。开始另一张桌子是正确的做法。
标签: mysql loops mysqli while-loop