对文章发表评论


Make comments on articles

我想对文章发表评论,但我有错误,你能纠正我的错误吗:

  • 我不在排队:$_SESSION['user_id'] = '';
  • 我的这条线有错误

    $database->insert->comments($comment);return$comment['_id'];

错误为:

  • 未定义的变量:中的数据库
  • 正在尝试获取中非对象的属性
  • 对中非对象的成员函数comments()的调用

谢谢

我的文件照片.php

<?php
try {
           $connection = new MongoClient();
           $database   = $connection->selectDB('test');
           $collection = $database->selectCollection('articles');
         } Catch(MongoException $e) {
           die("Failed to connect to database ".$e->getMessage());
}
         $cursor = $collection->find();
       ?>
<?php session_start(['user_id']); 
 $_SESSION['user_id'] = '';
?>
<article class="photo">
  <img src="french.jpg">
  <section class="comments">
    <article class="comment">
      <header>Jean-Raphael</header>
      Wouah cool
    </article>
    <article class="comment">
      <header>Gaëlle</header>
   JR lol
    </article>
    <form class="comment" action="" method="post">
      <input type="hidden" name="photo_comment" value="true" />
      <textarea name="comment">
      </textarea>
      <input type="submit" value="comment"/>
    </form>
  </section>
</article>
<?php
function process_comment_if_any_comment_posted ()
{
   $comment = get_posted_comment_if_any_and_secure();
   if(invalid_or_no_comment($comment)) return;
   insert_comment($comment);
}
process_comment_if_any_comment_posted();
function get_posted_comment_if_any_and_secure()
{
  $comment = array();
  if(! comment_posted()) return $comment;
  $text = check_and_secure($_POST, 'comment');
  if($text == "") return $comment;
  $comment['text'] = $text;
  $comment['author'] = $_SESSION['user_id'];

  global $photo;
  $comment['photo'] = $photo['_id'];
  return $comment;
}
function invalid_or_no_comment($comment)
{
  return empty($comment)
    || ! isSet($comment['text'])
    || (trim($comment['text']) == "");
}
function insert_comment($comment)
{
  $database->insert->comments($comment);
  return $comment['_id'];
}
function get_photo()
{
  $photo = array();

  return $photo;
}
$photo = get_photo();
function comment_posted()
{
   return isSet($_POST['photo_comment']);
}
function check_and_secure($T, $field)
{
  if(! isSet($T[$field])) return "";
  return htmlentities($T[$field]);
}

您得到的错误表明$database未定义,您在try-catch块中的文件顶部定义了它,但您必须将它带入insert_comment()函数的本地范围:

function insert_comment($comment)
{
  global $database;
  $database->insert->comments($comment);
  return $comment['_id'];
}

此外,正如Fred在评论中指出的,session_start()不接受任何参数。