对文章发表评论

时间:2015-04-09 17:42:01

标签: php mongodb

我想对文章发表评论,但我有错误可以纠正我的错误:

  • 我不喜欢这条线:$_SESSION['user_id'] = '';
  • 我的这行有错误

    $数据库 - >嵌件>注释(评论$);      返回$ comment ['_ id'];

错误是:

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

谢谢你

我的文件photo.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]);
}

1 个答案:

答案 0 :(得分:0)

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

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

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