PHP留言板应用程序

时间:2014-04-14 03:18:53

标签: php forms file file-io

使用简单的PHP表单(迷你留言簿),然后写入文本文件,一旦提交,生成的页面将以表格形式显示文本文件的内容。这是我的index.php

代码
<?php

echo "Please sign the guest book.";
echo "<form action='guestbook.php' method='POST'>";
echo "Name: <input type='text' name='guest' maxlength='15'><br>";
echo "Date Visted: <input type='text' name='date'><br>";
echo "<input type='submit' name='submit' value='Submit'>";
echo "</form><br>";

if(isset($_POST['submit'])){
    $myfile = "/tmp/jbgb.txt";
    $fh = fopen($myfile,'a');
    $guest = $_POST['guest'];
    $date = $_POST['date'];
    fwrite($fh, "<td>".$guest."<td>".$date."\n");
    fclose($fh);
    $data = NULL;
    }
?>

这是我的guestbook.php

<?php

echo "Jason's Guestbook<br>";
echo "<table border=1>";

$file = fopen("/tmp/jbgb.txt","r") or exit("Unable to open file!");
while(!feof($file))
    {
    echo "<tr>";
    echo fgets($file);
    echo "</tr>";
    }
fclose($file);
echo "</table>";
?>

我有两个小问题需要帮助。

  1. (在我的index.php文件中)当我在表单操作中放入guestbook.php时,该文件不会将数据发送到文本文件。当表单操作为空时,它将发送数据。

  2. 如果index.php页面被刷新,它将从上次输入任何数据时发送重复数据。提交或重新加载页面后,我需要帮助清除变量。

1 个答案:

答案 0 :(得分:1)

您的数据未被发送的原因是因为您在guestbook.php中没有任何代码来处理数据。

将index.php更改为:

<?php

echo "Please sign the guest book.";
echo "<form action='guestbook.php' method='POST'>";
echo "Name: <input type='text' name='guest' maxlength='15'><br>";
echo "Date Visted: <input type='text' name='date'><br>";
echo "<input type='submit' name='submit' value='Submit'>";
echo "</form><br>";

?>

将guestbook.php更改为:

<?php

if(isset($_POST['submit'])){
    $myfile = "/tmp/jbgb.txt";
    $fh = fopen($myfile,'a');
    $guest = $_POST['guest'];
    $date = $_POST['date'];
    fwrite($fh, "<td>".$guest."<td>".$date."\n");
    fclose($fh);
    $data = NULL;
}

echo "Jason's Guestbook<br>";
echo "<table border=1>";

$file = fopen("/tmp/jbgb.txt","r") or exit("Unable to open file!");
while(!feof($file))
    {
    echo "<tr>";
    echo fgets($file);
    echo "</tr>";
    }
fclose($file);
echo "</table>";
?>

现在数据处理已移至正确的目的地,它应该可以工作!