I have problem to make a code for connecting to DB and after that close the connections.
my DB class is below:
class DataBase {
private $conn;
private $info;
private $db;
public function __construct ($servername=DB_SERVER, $user=DB_USER, $pass=DB_PASS, $db=DB_DATABASE) {
$this->db = $db;
$this->conn = new mysqli($servername,$user,$pass, $this->db);
if (!$this->conn)
{
if ($this->conn->connect_error) {
$this->info = "ERROR CODE=DB100: Connection failed <br> " . $conn->connect_error;
$this->close();
echo $this->getInfo();
}
else {
$this->info = "ERROR CODE=DB101: Connection failed <br> ";
$this->close();
echo $this->getInfo();
}
}
}
public function getInfo () {
return $this->info;
}
// send sql to database
public function sendQuery ($sql, $numr=null, $start=null) {
if ($numr) {
if ($start)
$sql .= " LIMIT $start, $numr";
else
$sql .= " LIMIT $numr";
}
$this->conn->set_charset("utf8");
$result = $this->conn->query($sql);
if ($result == true) {
return $result;
}
else {
$this->info = "ERROR CODE=DB102: Sql query not work <br>".$this->conn->error;
$this->close();
echo $this->getInfo();
return false;
}
}
public function sendQueryNoneCahrSet ($sql, $numr=null, $start=null) {
if ($numr) {
if ($start)
$sql .= " LIMIT $start, $numr";
else
$sql .= " LIMIT $numr";
}
$result = $this->conn->query($sql);
if ($result == true) {
return $result;
}
else {
$this->info = "ERROR CODE=DB103: Sql query not work <br>".$this->conn->error;
$this->close();
echo $this->getInfo();
return false;
}
}
// send sql query safe to avoid sql injection.
public function getConn () {
return $this->conn;
}
public function getDataBase (){
return $this->db;
}
// This method close the connection
public function close () {
$this->conn->close();
}
function __destruct() {
$this->close();
}
}
and when I run this code:
$con = @new DataBase();
$r = $con->sendQuery($sql);
$con->close();
I got this error:
Warning: mysqli::close(): Couldn't fetch mysqli in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\automasion\admin\protected\componets\database.php on line 102
program run correctly and set data into DB but this Error happen.
error point to:
$this->conn->close();
in my DB Connection code.