显然,我是一名网页设计师新手。我使用 php 和 sql 来完成所有幕后工作,但我想要一个视觉上吸引人且功能齐全的注释系统。
现在我只使用 HTML 表单,但它们看起来不太好。我应该使用 JavaScript 吗?有什么建议可以帮助我开始吗?
最佳答案
如果您只是想要评论而不是寻求学习经验,那么可以走捷径并使用 Disqus !设置起来非常简单。
Right now I am just using HTML forms but they don't look very good. Should I be using javascript?
如果您使用 JavaScript,无论如何您都会在其中的某个地方拥有 HTML 表单。
基本上你会想要:
- 创建 SQL 表
comments
- 创建 PHP 脚本“comment.php”
- 将代码添加到所有显示评论的页面底部...
- ...和 HTML
<form>
到您想要发表评论的所有页面的底部,并带有action
属性指向您的“comment.php”脚本。
创建 SQL 表 comments
在数据库中创建一个包含以下列的表:
- id - 唯一标识符
- url - 被评论的页面的 URL。
- 作者 - 留下评论的人
- comment - 留下的评论
一点 SQL:
CREATE TABLE `comments`
( `id` INT NOT NULL AUTO_INCREMENT,
`url` VARCHAR(255) NOT NULL ,
`author` VARCHAR(255) NOT NULL ,
`comment` TEXT NOT NULL ,
PRIMARY KEY (id)
)
不保证我的语法是完美的;)
创建 PHP 脚本“comment.php”
让它响应 POST
请求并向表中插入一行 comments
。 (为什么POST
?阅读Safe Methods)
<?php
$db = DB::connect(...);
// I'm being a little lazy with the intricacies of PHP-DB interaction...
// Be sure to validate the input a little.
// You'll want to take some measures to prevent spoofing.
$db->insert("INSERT INTO `comments` (`url`, `author`,`comment`) VALUES (?,?,?)", array($_POST['url'], $_POST['author'], $_POST['comment']));
header("Location: ".$_POST['url']); // redirect back to the commented page
// actually, I'm being lazy;the Location header is supposed to be a full url including protocol and domain etc
?>
请注意I've used placeholders ?
in the SQL ...
将代码添加到所有显示评论的页面底部
在所有带有评论的页面底部,添加类似...的内容
<?php
$db = DB::connect(...);
// I'm being a little lazy with the intricacies of PHP-DB interaction...
$result = $db->query("SELECT * FROM `comments` WHERE `url`=?", array($_SERVER['REQUEST_URI']));
while($row = $result->fetchRow()) }
echo "<div class=\"comment\">";
echo "<div class=\"author\">Comment By:".htmlentities($row['author'])."</div>";
echo htmlentities($row['comment']);
echo "</div>";
}
?>
注意 htmlentities
的使用防止XSS .
添加 HTML <form>
到所有页面的底部
现在,为了让用户能够添加评论,您需要一个 HTML <form>
.
<form method="post" action="/path/to/comments.php">
<label for="author">Your name:</label><input name="author" id="author" />
<textarea name="comment"></textarea>
<input type="hidden" name="url" value="<?php echo htmlentities($_SERVER['REQUEST_URI'])?>" />
<input type="submit" />
</form>
但是,这样做时,您只有文本(没有很酷的重力或任何东西),而且您实际上只是信任人们的名字(没有 OpenID 身份验证)。您的评论也没有任何格式(它们都是纯文本)。
所有这些都可以通过 Disqus 来涵盖。
关于php - 如何在我的博客上编写评论框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3017531/