This question already has an answer here:
I am trying to perform an insert query using the DB connection (singleton pattern used) but I keep getting HTTP error 500 But if I try to perform the insert query using a normal DB connection, like creating a new connection every time, rather than using the same connection everywhere, it does show results
Meanwhile, I tried to perform Select query which works perfectly fine
<?php
class DBtest
{
private $_mysqliConnectionString;
public static $instance;
private $servername;
private $username;
private $password;
private $dbase;
public static function getInstance() //to get only one instance of the DB connection, singleton pattern applied
{
if(!isset(self::$instance))
{
self::$instance=new DBtest;
}
return self::$instance;
}
private function __construct()
{
$this->servername = "";
$this->username = "";
$this->password = "";
$this->dbase = "";
$this->_mysqliConnectionString = new mysqli($this->servername, $this->username, $this->password,$this->dbase);
if($this->_mysqliConnectionString->connect_error)
{
die($this->_mysqliConnectionString->connect_error);
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$this->_mysqliConnectionString->set_charset("utf8mb4");
}
private function __destruct()
{
if ($this->_mysqliConnectionString) $this->_mysqliConnectionString->close();
}
private function __clone() {}
public function ReturnConnectionString() //returns connection
{
return $this->_mysqliConnectionString;
}
public function query($sql)
{
$conn= $this->ReturnConnectionString() ;
if (mysqli_query($conn,$sql))
{
echo "<br>Changes have been successfully implemented in the DB";
}
else
{
echo "<br>Error: " . $sql . "<br>" . $conn->error;
}
}
}
$DBobject = DBtest::getInstance();
$sql ="INSERT INTO Users (id,name, email, password) VALUES (110,'abc','Smth@live.kr','BTS')";
$DBobject->query($sql);
?>
Aucun commentaire:
Enregistrer un commentaire