PHP singleton mode encapsulates MySQL classes

class MysqlConn { 
  //Define a private static property to store the instantiated object
private static $dbcon;
  //Define a private static property for the connection to the database
private static $conn;
  //Define a private Deconstruction function to connect to the database
private function __construct()
{
self::$conn = mysqli_connect($host,$username,$password,$dbname) or die('Connection failed:'.mysqli_error().mysqli_errno()) ;
}
  //Define a private clone method
private function __clone()
{
// TODO: Implement __clone() method.
}
  //Public static method to return class instance
public static function getInstance(){
if (!self ::$dbcon){
self::$dbcon = new self();
}
return self::$dbcon;
}
  //You can define various functions of MySQL later
public function search($sql){
$result = mysqli_query(self::$conn,$sql);
return mysqli_fetch_assoc($result);
}
}
//call method
$conn = MysqlConn::getInstance();
$sql = "select * from `table_name`";
$rows = $conn->search($sql);
echo '<pre>';
var_dump($rows);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324995451&siteId=291194637