数组到字符串问题,PHP


Array to string issue , PHP

我正在研究一个评论系统,目前非常基本。 尝试从数据库获取注释时遇到错误。

令我好奇的是,这与我在类似页面上使用的代码几乎相同,并且没有错误,但是......

流程是

表格:

<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;    
 }

名字和ID等都还行。 但是在要求评论时,我得到**Notice: Array to string conversion in bla**并且没有任何输出。我已经转储了变量,它肯定在那里,我只是不确定如何获取它或为什么它不像我期望的那样工作。

我也尝试将 db 更改为 varchar(作为菜鸟测试)和相同的结果。

你提到的"blabla"应该是你在哪里寻找问题的最大线索。它准确地告诉您错误发生在这一行中 - 所以看看这一行。

看到这个:

echo $comments;

我假设你想这样做:

echo $comm;

$comments数组,则将注释的文本分配给$comm