简体   繁体   中英

How to use MySQLi in a class

I have 2 files

MySQLi.php

$MySQLi = new mysqli($DB_ServerName, $DB_UserName, $DB_Password, $DB_Name); 
    if($MySQLi->connect_error) 
    { 
        ... 
    } 
    else 
    { 
        ... 
    }  

Articles.php

class Articles 
{ 
    public function AddArticle() 
    { 
        if ($MySQLi->query("INSERT INTO articles (Title, ArticleContent, Author) VALUES ('Title', 'Content', 'Author')") === TRUE) 
        { 
           ... 
        } 
        else 
        { 
            ... 
        } 
    } 
}

How can I use $MySQLi in Articles class? ‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎

As mentioned in comment, you should include connection object file to another file.

Another alternative is:-

1) Make connection class static to handle mysqli object.

class DBConnection {
    public static $con;
}
DBConnection::$con = new mysqli(YOUR_HOST, YOUR_USER, YOUR_PASS, YOUR_DB);

and in other file, call it statically as below:-

DBConnection::$con->query(...); // execute your query

2) You can also do it by creating class and object.

class Connection{
  public $conn;

  function __construct($host='YOUR_HOST',$user='YOUR_USER',$pass='YOUR_PASS',$db='YOUR_DB'){
     $this->conn = new mysqli($host, $user, $pass, $db);
  }
} 

then create object of Connection class

$object = new Connection(); // pass connection params if you want to overwrite default connection params

$object->conn->query(..); // execute your query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM