首页 > 解决方案 > 如何在主页上显示用户帖子

问题描述

因此,在页面顶部有一个区域供用户创建带有标题和正文的帖子。

<div class="write_post" id="write_post">
        <label for="post_title"><b>Title</b></label>
        <input type="text" placeholder="What are you calling this?" name="post_title" required>

        <label for="post_body">Body</label>
        <textarea name="post_body" id="post_body" rows="5" cols="80" placeholder="Write post here..." required></textarea>

        <button action="post.php" class="post_submit" type="submit">Post</button>
    </div>

目标是当他们单击帖子按钮时,它将在下面创建一个帖子。我尝试过使用 javascript 来提供帮助,但我不是 100% 确定该怎么做。朝着正确的方向推进会有所帮助。

标签: htmluser-interfacedisplay

解决方案


在这种情况下不需要使用 JavaScript – 您可以使用PHP并将表单数据保存在数据库中。

1. 在 PHP 文件中创建 HTML 表单

首先,将您的输入元素包装在一个表单中(我只保留了在这种情况下重要的元素):

index.php

<form action="comment.php" method="get">

        <input type="text" name="post_title">

        <textarea name="post_body"></textarea>

        <button type="submit">Post</button>

</form>

2.创建一个PHP文件来处理提交的表单数据

如您所见,表单有一个 action 属性,它指向一个名为comment.php的文件。这只是我选择的一个合适的名称,您可以随意命名 PHP 文件。

在这个新创建的 PHP 文件中,您必须处理提交的表单数据。请注意,PHP 文件只能在服务器上运行,而不能像 HTML 文件那样在您的 PC 上本地运行。我建议直接在您的网络服务器上的子文件夹中上传和测试。

可能的文件夹结构是:

test-folder
 |
 +-- index.php
 |
 +-- comment.php

2.编辑PHP文件并将数据保存到数据库

打开 PHP 文件并添加以下内容:

comment.php

2.1 获取表单数据


?php

/* 
 * Receive the submitted form data and assign it to variables
 */


$comment_title = $_GET["post_title"]; // same as the name attribute in HTML
$comment_body = $_GET["post_body"];

2.2 创建新数据库

我们现在有了数据,但我们也想保存它。像这样的数据通常保存在数据库中。大多数托管服务提供商都允许您非常轻松地创建一个。

你的数据库应该有这样的结构:

comments
 |
 +-- ID (auto increment)
 |
 +-- comment_title
 |
 +-- comment_body
             

2.3 连接数据库

我们现在必须连接到我们的数据库来保存数据。
/* 
 * Connect to your database to save the form data
 */

$servername = "localhost"; // get this data from your hosting provider 
$username = "username";
$password = "password";

// create a new connection
$conn = new mysqli($servername, $username, $password);

// check if the connection succeeds
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

2.4 向数据库中插入数据

/* 
 * Insert the form data in to the database
 */

$sql = "INSERT INTO comments (comment_title, comment_body)
VALUES ('".$comment_title."','".$comment_body."',)";

$conn->close();

3. 显示保存的数据

现在我们只需要在 index.php 中显示保存的数据,我们可以通过遍历数据库中的行来实现。

index.php

/* 
 * Connect to your database and display the saved comments
 */

$servername = "localhost"; // get this data from your hosting provider 
$username = "username";
$password = "password";

// create a new connection
$conn = new mysqli($servername, $username, $password);

// check if the connection succeeds
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$result = mysql_query("SELECT comment_title, comment_body FROM comments");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    echo $row[0] . $row[1];  
}


推荐阅读