gpt4 book ai didi

php - 如何以名称 "Anonymous"将评论保存到数据库?

转载 作者:行者123 更新时间:2023-11-30 23:59:54 26 4
gpt4 key购买 nike

留言簿的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>

代码差不多准备好了,但我有一个问题。

根据问题规范,如果用户没有注明姓名,我们需要将他的评论以“Anonymous”的名字保存到数据库中。如何实现?提前谢谢你。

最佳答案

 if(!empty($_POST['comment'])) {
/* this is used to check whether author variable is empty or not*/
$author = (!empty($_POST['author'])) ? trim($_POST['author']) : 'Anonymous';
$stmt = $dbConn->prepare('INSERT INTO comments(`author`, `comment`) VALUES(:author, :comment)');
$stmt->execute(array('author' => $author , 'comment' => $_POST['comment']));
header("location: /index.php");
}

关于php - 如何以名称 "Anonymous"将评论保存到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54146554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com