php - 初学者使用 php 创建留言簿,将信息记录到文本文件并在单独的页面上显示数据

标签 php html arrays forms text-files

我是一名 php 初学者,我正在努力创建一个留言簿页面,该页面将接受用户的姓名和电子邮件地址。他们提交表单后,脚本会将此数据写入文本文件。然后用户可以查看所有留言簿条目。这是我遇到问题的地方。

留言簿页面正在根据需要创建表格数据,但姓名和电子邮件部分未调用正确的数据。我正在使用 explode 方法,我认为那是我混淆自己并破坏程序的地方。我在这里查询并没有发现任何特定于此问题的内容。我还仔细阅读了文档,结果却让自己更加困惑。谁能告诉我哪里出错了?我在下面包含了这两个文件的源代码:

签名簿.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
       Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
       <html xmlns="http://www.w3.org/1999/xhtml">
       <head>
       <title>Post Message</title>
       <meta http-equiv="content-type"
            content="text/html; charset=iso-8859-1" />
       </head>
       <body>

<?php 

if (isset($_POST['submit'])) {
       $Name = stripslashes($_POST['name']);
       $Email = stripslashes($_POST['email']);

       $Name = str_replace("~", "-", $Name);
       $Email = str_replace("~", "-", $Email);
       $MessageRecord = "$Name~$Email\n";
       $MessageFile = fopen("Guestbook/messages.txt", "ab");
       if ($MessageFile === FALSE)
            echo "There was an error saving your
                 entry.\n";
       else {
            fwrite($MessageFile, $MessageRecord);
            fclose($MessageFile);
            echo "Thank you for signing the Guest Book!\n";
       } 
}

?>

<h1>Please Sign the Guest Book</h1>
<hr />
<form action="sign-book.php" method="POST">
<span style="font-weight:bold">Name:</span>
     <input type="text" name="name" />
<span style="font-weight:bold">Email:</span>
     <input type="text" name="email" /><br /><br />
<input type="submit" name="submit"
     value="Sign Guest Book" />
<input type="reset" name="reset"
     value="Reset Form" />
</form>
<hr />
<p>
<a href="guestbook.php">View Previous Entries</a>
</p>

       </body>
       </html>

留言本.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
       Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
       <html xmlns="http://www.w3.org/1999/xhtml">
       <head>
       <title>Message Board</title>
       <meta http-equiv="content-type"
            content="text/html; charset=iso-8859-1" />
       </head>
       <body>

<h1>Our Guestbook</h1>
<?php

if (isset($_GET['action'])) {
     if ((file_exists(
          "Guestbook/messages.txt")) &&
          (filesize(
          "Guestbook/messages.txt") != 0)) {
          $MessageArray = file(
               "Guestbook/messages.txt");
          switch ($_GET['action']) {
               case 'Delete Message':
                if (isset($_GET['message'])) {
                $Index = $_GET['message'];
                unset($MessageArray[$Index]);
                $MessageArray = array_values($MessageArray);
                }
                break;
               case 'Remove Duplicates':
                    $MessageArray = array_unique($MessageArray);
                    $MessageArray = array_values($MessageArray);
                    break;
               case 'Sort Ascending':
                    sort($MessageArray);
                    break;
                   case 'Sort Descending':
                    rsort($MessageArray);
                    break;
          } 

          if (count($MessageArray)>0) {
               $NewMessages = implode($MessageArray);
               $MessageStore = fopen("Guestbook/messages.txt", "wb");
               if ($MessageStore === false)
                    echo "There was an error
                         updating the message
                         file\n";
               else {
                    fwrite($MessageStore,
                         $NewMessages);
                    fclose($MessageStore);
               }
} else
         unlink("Guestbook/messages.txt");   
         }
  }  

if ((!file_exists("Guestbook/messages.txt"))
         || (filesize("Guestbook/messages.txt")
         == 0))
         echo "<p>There are no entries
              logged.</p>\n";
    else {
         $MessageArray = file("Guestbook/messages.txt");
         echo "<table
              style=\"background-color:lightgray\"
              border=\"1\" width=\"100%\">\n";

         $count = count($MessageArray);

         for ($i = 0; $i < $count; ++$i) {
            $CurrMsg = explode("~", $MessageArray[$i]);
            $KeyArray[] = $CurrMsg[0];
            $ValueArray[] = $CurrMsg[1];
            $KeyMessageArray = array_combine($KeyArray, $ValueArray);
         }

         $Index = 1;

         foreach($KeyMessageArray as $Message) { 
            $CurrMsg = explode("~", $Message); 
            echo "<tr>\n";
                echo "<td width=\"5%\"
                     style=\"text-align:center\"><span 
                     style=\"font-weight:bold\">" . 
                     $Index . "</span></td>\n";
          echo "<td width=\"85%\"><span
               style=\"font-weight:bold\">
               Name:</span> " .
               htmlentities($KeyArray[1]) . "<br />";
          echo "<span style=\"font-weight:bold\">
               Email:</span> " . htmlentities($CurrMsg[0]) .
               "<br />";
                echo "<td width=\"10%\" 
                     style=\"text-align:center\">" . 
                     "<a href='guestbook.php?" . 
                     "action=Delete%20Message&" . 
                     "message=" . ($Index - 1) . 
                     "'>Delete This Entry</a>" . 
                     "</td>\n";
                echo "</tr>\n"; 
            ++$Index; 
            next($KeyMessageArray);
        }
         echo "</table>\n";
    }


?>
<p>
<a href="sign-book.php">
Log Another Entry</a><br />
<a href="guestbook.php?action=Sort%20Ascending">
Sort Subjects A-Z</a><br />
<a href="guestbook.php?action=Sort%20Descending">
Sort Subjects Z-A</a><br />
<a href="guestbook.php?action=Remove%20Duplicates">
Remove Duplicate Messages</a><br />
</p>   

       </body>
       </html>

最佳答案

你已经通过~在这里展开了$MessageArray[$i]:

for ($i = 0; $i < $count; ++$i) {
    $CurrMsg = explode("~", $MessageArray[$i]);
    $KeyArray[] = $CurrMsg[0];
    $ValueArray[] = $CurrMsg[1];
    $KeyMessageArray = array_combine($KeyArray, $ValueArray);
}

所以,现在您在 $KeyArray 中拥有所有姓名,在 $ValueArray 中拥有所有电子邮件。 (顺便说一下 - 如果你的名字会被重复,例如 Paul, Paul, John - 糟糕) 尽管如此,接下来你要做的是:

foreach($KeyMessageArray as $Message) { 
    $CurrMsg = explode("~", $Message); 

但为什么要这样做,因为 $Message 已经是一封电子邮件,而且里面绝对没有 ~!

你应该这样使用foreach:

foreach($KeyMessageArray as $name => $email) { 
     // do stuff
}

更新关于名称:

所以,正如我所说,当您的名字重复时,您的代码将无法按预期工作。为避免这种情况 - 不要使用名称作为键,只需使用名称和电子邮件作为数组的值:

for ($i = 0; $i < $count; ++$i) {
    $CurrMsg = explode("~", $MessageArray[$i]);
    // add both values to array:
    $KeyMessageArray[] = array(
        'name' => $CurrMsg[0],
        'email' => $CurrMsg[1],
    );
}

// next - iterate:
foreach($KeyMessageArray as $data) { 
    echo 'name is ' . $data['name'] . ', email is ' . $data['email'];
    // do stuff
}

甚至更进一步 - 您可以在一个循环中完成所有事情:

for ($i = 0; $i < $count; ++$i) {
    $CurrMsg = explode("~", $MessageArray[$i]);
    echo 'name is ' . $CurrMsg[0] . ', email is ' . $CurrMsg[1];
    // show some table stuff
}

关于php - 初学者使用 php 创建留言簿,将信息记录到文本文件并在单独的页面上显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32936770/

相关文章:

PHP:更改时间格式 15:30:00 到 3:30PM

php - 在列表中分组 - php

javascript - 切换 php 生成的 div 元素

c - int a[9] 和 a[3][3] 的区别

python - Numpy arange float 不一致

php - 在javascript函数参数中插入变量

php - 每次都会出现 XAMPP 访问禁止错误

javascript - 我可以创建一个指向当前页面的 html 链接而不刷新到顶部吗?

html - 我怎样才能使宽度最大 100%?当我同时使用 PC 和 iPhone 查看时?

php - 使用 PHP 循环遍历数组