duangou1933
duangou1933
2014-04-14 03:18

PHP留言板应用程序

  • file
  • file-io
  • php
  • forms
已采纳

Working on a simple php form (mini guestbook) it is to write to a text file then, once submitted, the resulting page will display the contents of the text file in table form. Here is my code of 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."
");
    fclose($fh);
    $data = NULL;
    }
?>

Here is my 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>";
?>

I have two small issues that I need some help with.

  1. (In my index.php file) When I put guestbook.php in my form action, the file will not sent the data to the text file. When the form action is blank it will send data just fine.

  2. If the index.php page is refreshed it will send duplicate data from the last time any data was entered. I need help to clear out the variables once the page is submitted or reloaded.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doz95923 doz95923 7年前

    The reason your data isn't being sent through is because you don't have any code in guestbook.php to handle the data.

    Change index.php to this:

    <?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>";
    
    ?>
    

    And change guestbook.php to this:

    <?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."
    ");
        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>";
    ?>
    

    Now that the data handling is moved to the correct destination, it should work!

    点赞 评论 复制链接分享

为你推荐