我正在开发一个评论系统,目前非常基本。尝试从数据库获取评论时遇到错误。
我的好奇心是,这与我在类似页面上使用的代码几乎相同,然后没有错误,但是......
流量是
HTML表格:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']."?id=".$id?>" id="addComment" class="form-horizontal">
<textarea class="span10" name="comment" id="comment" rows="3" class="required"></textarea>
<button type="submit" name="addComment" id="addComment" class="btn btn-primary btn-large">Add Comment</button>
</form>
PHP的页面顶部:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//have id already
$name = trim(htmlspecialchars($_POST['name']));
$comment = trim(htmlspecialchars($_POST['comment']));
$articleComments->addComment($id, $name, $comment);
}
?>
功能:
//add comment to an article(check ip for bans(later))
public function addComment($articleId, $name, $comment){
$query = $this->db->prepare("INSERT INTO `articleComments`
(`articleId`,`name`,`date`,`comment`)
VALUES (?,?,?,?)");
$date = date ("Y-m-d H:i:s", time());
$query->bindValue(1, $articleId);
$query->bindValue(2, $name);
$query->bindValue(3, $date);
$query->bindValue(4, $comment);
try{
$query->execute();
}catch(PDOException $e){
die($e->getCode());
}
}
然后是输出函数:
//get all comments
public function getAllComments($aticleId){
$query = $this->db->prepare("SELECT * FROM `articleComments` WHERE `articleId` = ?");
$query->bindValue(1,$aticleId);
try{
$query->execute();
return $query->fetchAll();
}catch (PDOException $e){
die($e->getMessage());
}
}
其次是输出:
$comments = $articleComments->getAllComments($id);
foreach ($comments as $c){
$commentId = $c['id'];
$name = $c['name'];
$date = $c['date'];
$comm = $c['comment'];
$like = $c['likes'];
//echo "Name: " . $name;
//echo " Date: " . $date;
echo $comments;
}
名字和身份证等都出来了。但是**Notice: Array to string conversion in bla**
在征求评论时我没有得到任何输出。我已经转储了变量并且它肯定存在,我只是不确定如何获取它或为什么它不像我期望的那样工作。
我也尝试将 db 更改为 varchar (作为菜鸟测试),结果相同。