首页 > 解决方案 > 如何以“匿名”的名义将评论保存到数据库?

问题描述

留言簿有以下 PHP 代码:

<?php require_once('config.php');

if(!empty($_POST['comment'])) {
    $stmt = $dbConn->prepare('INSERT INTO comments(`author`, `comment`) VALUES(:author, :comment)');
    $stmt->execute(array('author' => $_POST['author'], 'comment' => $_POST['comment']));
    header("location: /index.php");
}

$stmt = $dbConn->prepare('SELECT author, comment, created_at FROM comments ORDER BY id DESC');
$stmt->execute();
$comments = $stmt->fetchAll();
;?>

<title>Comments Page</title>
<link rel='stylesheet' href='style.css'>

<div id='comments-header'>
    <h1></h1>
</div>
<div id='comments-form'>
    <h3>Please add your comment</h3>
    <form method='post'>
        <div>
            <div>
                <input type="text" name="author" placeholder="Enter your name">
            </div>
            <div>
                <textarea name='comment' placeholder="Enter your comment"></textarea>
            </div>
            <div>
                <br>
                <input type='submit' name='submit' value='Save'>
            </div>
        </div>
    </form>
</div>
<div id='comments-panel'>
    <h3>Comments:</h3>
    <?php foreach ($comments as $comment): ?>
        <p><?=$comment['comment']?>
            <span class='comment-date comment-author'>
                (<?=$comment['author']?> <?=$comment['created_at'];?>)
            </span>
        </p>
    <?php endforeach; ?>
</div>

代码几乎准备好了,但我有一个问题。

根据问题规范,如果用户没有指明他的姓名,我们需要将他的评论以“匿名”的名称保存到数据库中。如何实施?先感谢您。

标签: phpmysql

解决方案


使用如果。

if (!empty($_POST["author"]))
    $author = $_POST["author"]);
else
    $author = "Anon";

或者提供相同的三元表达式:

$author = ((!empty($_POST["author"])) ? ($_POST["author"]) : ("Anon"));

如果您使用的是 php 7,则可以使用它,它提供相同的:

$author = ((!empty($_POST["author"])) ?? ("Anon"));

然后在你的参数中:$stmt->execute(array('author' => $author ...

请注意,您不需要在三元表达式的每个元素周围加上括号。这是我的一个老习惯。


推荐阅读