如何在另一个页面上的另一个类中访问mysqli连接?

时间:2012-06-20 05:00:43

标签: php mysql oop mysqli

如何在用户类中打开数据库连接,我可以在哪里进行数据库操作? 以及为什么需要在DBConnection类中定义内置的已创建函数.. ????

我创建了

  1. db.php中
  2. user.php的
  3. result.php
  4. db.php中的

    class DBConnection  
    {       
      protected $mysqli;
      private  $db_host="127.0.0.1";
      private  $db_name="test";
      private  $db_username="root";
      private  $db_password="";
    
      public function __construct()
        {
            $this->mysqli=new mysqli($this->db_host,$this->db_username,
                    $this->  db_password,$this->db_name) or die($this->mysqli->error);
    
             return $this->mysqli;
        }
    
    public function query($query)  // why i need to creat this function
         {
        return $this->mysqli->query($query);
         }
    
    public function real_escape_string($str)
     {
        return $this->mysqli->real_escape_string();
     }
    
    
       function __destruct(){
         //Close the Connection
         $this->mysqli->close();
        }
    }
    ?>
    
    User.php中的

    <?php
      require "db.php"; 
    
      class User {  
    
      public function __construct($conn)
    {
        $this->mysqli=$conn;
    
    }
    
       public function addUser($name,$username,$email,$pwd)
       {
         $query="  ";
    
         $res=$this->mysqli->query($query);
    
      //pls chek the query function in DBConnection,what is the need to define query               >       function in DBConnection ?
    
        return $res;
        }
       }    
    ?>
    
    在result.php中

        <?php
    
          require "user.php";
    
          $conn=new DBConnection();
    
          if(isset($_POST['submit']))
      {
    
     $name = $conn->real_escape_string(trim(strip_tags($_POST['name'])));
       $username =  $conn->real_escape_string(trim(strip_tags($_POST['username'])));
       $email =     $conn->real_escape_string(trim(strip_tags($_POST['email'])));
       $password    = $conn->real_escape_string(trim(strip_tags($_POST['pass'])));
    
    //echo $name."".$username."".$email."".$password;
      $uObj=new User($conn);
      $uObj->addUser($name,$username,$email,$password);
    
    
    echo " hi your name is <I>".$name."</I> and your email ID is <I>".$email."</I>";
            }
    
    
    ?>
    

1 个答案:

答案 0 :(得分:1)

您的DBConnection课程需要一个额外的方法:

public function getLink()
{
    return $this->mysqli;
}

您的原始User类似乎是DBConnection的子类,因为mysqli上的DBConnection属性是protectedUser类有一个parent::__construct()电话。

最好使用依赖注入,因此您的User类将通过构造函数接收其数据库连接:

public function __construct(DBConnection $db)
{
    $this->mysqli = $db->getLink();
}

然后从您的代码中运行:

$db = new DBConnection;
$uObj = new User($db);