mysqli面向对象编程

时间:2014-09-23 10:30:36

标签: php oop mysqli

我正在努力让我的登录主页工作。在第一次我使用mysql构建我的查询但我总是得到错误“查询是空的”所以我决定转换到mysqli。我现在收到错误“警告:mysqli_query()期望至少2个参数”。 如何从类“database2”中的方法“connect()”调用我的“mysqli_query($ db,$ string)”中的第一个参数“$ db”以使其工作? 我试过“$ result = $ this-> cxn-> query($ query)”,但后来我收到错误“致命错误:调用未定义的方法Database2 :: query()

<?php

class Login
{
    private $username;
    private $password;
    private $cxn;    // Database object.

    function __construct($username, $password)
    {
        // Set data
        $this->setData($username, $password);

        // connect to db
        $this->connectToDb();

        //get Data
        $this->getData();
    }

   private function setData($username, $password){

             $this->username = $username;
             $this->password = $password;

            }

    private function connectToDb(){

            include 'models/database2.php';
            $vars = "include/vars.php";
            $this->cxn = new Database2($vars);

            }

    private function getData(){

          $query ="SELECT 'username', 'password' FROM 'users' WHERE 'username' = '$this->username'
                                    AND 'password' = '$this->password'";

           $result = mysqli_query($query) or die(mysql_error());
           $num_row = mysqli_num_rows($result); 

                 if ($num_row>1) {
                    return TRUE;
                 }else{
                      throw new Exception("The query was not successful!");
                  }
              }

      function close(){
        $this->cxn->close_connect();
            }

}
?>

Database2类:

<?php


class Database2{


    private $host;
    private $user;
    private $password;
    private $database;

    function __construct($filename){
        if(is_file($filename)){
            include $filename;
        }else{
            throw new Exception("Error Processing Request");
            }
        $this->host     = $host;
        $this->user     = $user;
        $this->password =$password;
        $this->database =$database;

        $this->connect();       
      }

         public function connect(){
                      // connect to the server.
                     $db = new mysqli($this->host, $this->user, $this->password);    
                       if ($db->connect_errno) {
                           die("We are sorry, you could not be connected to the server,
                            plaese check your connection setting!");
                       }else{
                           echo "You are connected to the database";
                       }
                   }


      public function close_connect(){
        mysql_close();

      }
}


?>

我感谢任何帮助

1 个答案:

答案 0 :(得分:-2)

如果使用程序样式,则必须设置并使用&#34; $ db&#34; database2类中的变量。 在connect函数中设置变量:

$this->db = new mysqli($this->host, $this->user, $this->password); 

然后,您可以在database2对象中使用$ db

$result = mysqli_query($this->cxn->db, $query);