我正在创建一个原型电子商务网站,我在将访客名称保存到我的平面文件数据库“购买”时遇到了问题。
<body>
<h1>Confirm Selection</h1>
<form action="write.php" method="post">
<table>
<tr><th></th><th></th><th></th><th>Price</th></tr>
<?php
$visitor = $_POST['visitor'];
echo "<p>".'Hello '."<b>".$visitor."</b> ".'please confirm your purchase(s) below.'."</p>";
?>
</table>
上面的确认文件创建了一个名为$ visitor的变量,这是用户在上一个表单中输入的名称,我想接受这个变量,一旦用户确认他们的选择将其传递给“写” .php“要处理的文件并写入购买文件。
我的“write.php”文件的一部分在下面。
<?php
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$now = date(' d/m/y H:i:s ');
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("can't open file\n");
$content = $now . "|" . $partno . "|" . $name . "|" . $price . "\n";
if (!(fwrite($fh, $content))) {
echo "<p>ERROR: Cannot Write ($myFile)\n</p>";
exit;
} else {
echo "<p>Transaction Completed!</p>";
fclose($fh);
}
}
}
}
?>
答案 0 :(得分:0)
如果购买页面提交到write.php,则隐藏变量可能有效:
<form action="write.php" method="post">
<table>
<tr><th></th><th></th><th></th><th>Price</th></tr>
<?php
$visitor = $_POST['visitor'];
echo "<p>".'Hello '."<b>".$visitor."</b> ".'please confirm your purchase(s) below.'."</p>";
?>
<input type="hidden" name="visitor" value="<?=$visitor?>"/> <!-- added line to send visitor -->
</table>
所以在你的write.php中:
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$visitor = $_REQUEST['visitor']; // added line, now you have visitor
$now = date(' d/m/y H:i:s ');
PS:您可能需要htmlentities功能,因为用户可以为访问者输入有趣的字符:
<input type="hidden" name="visitor" value="<?=htmlentities($visitor)?>">