php - 如何以“匿名”的名义将评论保存到数据库?
问题描述
留言簿有以下 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>
代码几乎准备好了,但我有一个问题。
根据问题规范,如果用户没有指明他的姓名,我们需要将他的评论以“匿名”的名称保存到数据库中。如何实施?先感谢您。
解决方案
使用如果。
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 ...
请注意,您不需要在三元表达式的每个元素周围加上括号。这是我的一个老习惯。
推荐阅读
- javascript - 如何更改 Nuxt 构建的入口点?
- python - OpenCV triangulatePoints() 得到负深度,我做错了什么?
- javascript - 节点js追加到现有的csv文件所有数据都被追加到一个单元格
- git - git:合并方向之间的差异
- python - 熊猫数据框 KeyError
- r - 如何将变量名称和函数调用的 tibble 传递给 tibble
- c - 为什么代码在这个 char 比较中没有产生任何结果?
- matlab - 用约束条件在 MATLAB 中用向量的线性组合拟合数据
- python - Python cx_Oracle 模块:无法在代码中格式化查询
- c# - WinForms:没有挂起的 SuspendLayout() 调用