0

我正在创建一个原型电子商务网站,我在将访问者姓名保存到我的平面文件数据库“购买”时遇到问题。

<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>&nbsp;".'please confirm your purchase(s) below.'."</p>";
            ?>

        </table>

上面的确认文件创建了一个名为 $visitor 的变量,它是用户在之前的表单中输入的任何名称,然后我想使用这个变量,一旦用户确认他们的选择,将其传递给“write.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);
                    }
                }
            }
        }
        ?>
4

1 回答 1

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>&nbsp;".'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)?>">
于 2013-03-14T14:37:03.150 回答