使用类插入数据库

时间:2014-03-26 14:05:46

标签: php class

我在这里做错了什么?

错误:

mysql_query() expects parameter 2 to be resource, string given in <b>php_includes/subscribers.php</b> on line <b>11</b><br />

<b>Warning</b>:  mysql_query() expects parameter 2 to be resource, string given php_includes/comments.php</b> on line <b>19</b><br />

{"user":null,"comment":null,"error":true,"Comment":null}

代码:

<?php

if(isset($_POST['task'])&& $_POST['task']=='comment_insert'){   
   require_once("php_includes/db_conx.php");
   $userName= $_POST['userName'];
   $userId=(int)$_POST['userId'];
   $comment=addslashes(str_replace("\n" , "<br>" , $_POST['comment']));
   $std= new stdClass();
   $std->user=null;
   $std->comment=null;
   $std->error=false;
   require_once("comments.php");

   if(class_exists('Comments') && class_exists('Subscribers'))
    {
      $userInfo = Subscribers::getSubscriber($userId);
       if($userId == null)

      { 
       $std->error=true;
       }

       $commentInfo = comments ::insert ($comment,$userId);
         if($commentInfo == null)
         {      
         $std->error=true;
         }

         $std -> user = $userInfo;
         $std -> Comment = $commentInfo;


      }

     echo json_encode($std);    

   }

     else{

      header('location:/jobs_article.php');
      }

     ?>


    /////////////////////////////////subscribers.php//////////////////////

<?php
require_once("comments.php");

  class Subscribers{
  public static function getSubscriber($userId ){
  require_once("db_conx.php");

  $sql = " select * from users where id = $userId"; 
  $query = mysql_query($db_conx,$sql);

  if($query){
      if( mysql_num_rows ($query)==1 )

    {
    return  mysql_fetch_object($query);  
     }  

     }  return null;

  }

 }?>
  /////////////////////////////////end of subscribers.php//////////////////////



///////////////////////////////////////////comments.php////////////////////////////

 <?php
  require_once("db_conx.php");
  require_once("subscribers.php");

   class Comments {
    public static function getComments($userId ){
    //return a stdclass object from the database
}


  public static function insert($userId){       
     $comment=addslashes($comment); 
     $sql= "INSERT into job_article_comments VALUES('' , '$comment' , '$userId')";
     $query=mysql_query($db_conx,$sql);


         if($query){                
           $insert_id = mysql_insert_id();
           $std = new stdClass();
           $std->comment_id = $insert_id;
           $std->comment = $comment;
           $std->userId = $userId;
           return $std;
      }

     return null;

}



   }?>///////////////// ///end of comment.php////////////////

2 个答案:

答案 0 :(得分:0)

您的参数是倒退的。 sql查询是第一个参数,db资源是第二个参数:

$query = mysql_query($db_conx,$sql);

应该是

 $query = mysql_query($sql, $db_conx);

答案 1 :(得分:0)

阅读mysql_query函数的文档,你就会看到你做错了什么。

http://www.php.net/manual/en/function.mysql-query.php

注意:您使用的是MySQL,而不是像标记的那样使用MySQLi。