这是用于连接MYSQL的db.php文件。我正在使用1.所有实例之间共享的单个实例2.db连接配置变量3.此方法必须是静态的,并且如果对象不存在,则必须返回对象的实例。4.克隆和唤醒方法防止外部实例化 Singleton 类的副本,从而消除重复对象的可能性。
<?php
include('config.php');
class db extends mysqli {
// single instance of self shared among all instances
private static $instance = null;
// db connection config vars
private $user = DBUSER;
private $pass = DBPWD;
private $dbName = DBNAME;
private $dbHost = DBHOST;
//This method must be static, and must return an instance of the object if the object
//does not already exist.
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
// The clone and wakeup methods prevents external instantiation of copies of the Singleton class,
// thus eliminating the possibility of duplicate objects.
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
private function __construct() {
parent::__construct($this->dbHost, $this->user, $this->pass, $this->dbName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
parent::set_charset('utf-8');
}
public function dbquery($query)
{
if($this->query($query))
{
return true;
}
}
public function get_result($query)
{
$result = $this->query($query);
if ($result->num_rows > 0){
while ($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
} else
return null;
}
}
?>
这是插入带有 Escape 用户输入的电缆以确保安全
<?php
$Institute_Name = mysqli_real_escape_string($conn, $_REQUEST['Institute_Name']);
$Institute_Address = mysqli_real_escape_string($conn, $_REQUEST['Institute_Address']);
?>
我需要如何从实例调用$conn
$conn = getInstance();
我试试这个。这是行不通的我需要它来插入代码
$query= "INSERT INTO `institute` ( Institute_Name, Institute_Address, ) VALUES ('$Institute_Name', '$Institute_Address')";
你应该使用
$conn = db::getInstance();