下面是我的电子商务网站(原型)中使用的一个 php 文件,用于编写客户选择的项目并将他们的选择存储在平面文件数据库中。尽管为每个选定的项目都打印了逻辑,但逻辑工作正常,echo "Order Submitted!;
例如如果选择了 4 个项目,则此行打印 4 次,我只需要打印一次。知道如何实现吗?
<body>
<table>
<?php
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
} else {
echo "<h1>Transaction Completed!</h1>";
}
date_default_timezone_set('Europe/London');
$now = date(' d/m/y H:i:s ');
$visitor = $_POST['visitor'];
foreach ($_POST as $varname => $varvalue) {
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname) {
$myFile = "purchases.txt";
$fh = fopen($myFile, 'a') or die("ERROR: Failed to open purchases file!\n");
$content = $now . "|" . $visitor . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot write to file($myFile)\n</p>";
exit;
} else {
echo "<p>Order Submitted!</p>";
fclose($fh);
}
}
}
}
?>
</table>
<input type="button" onClick="parent.location='home.php'" value="Return Home">
<input type="button" onClick="parent.location='items.php'" value="New Purchase">
如果选择了 2 个项目,则输出为:
交易完成 订单提交!提交订单!