Metode Anda:
public function db_connect() {
$connection = mysqli_connect(self::$db_host, self::$db_user, self::$db_pass, self::$db_name) or die("Error " . mysqli_error($connection));
echo "Conexión realizada". "<br>";
}
tidak mengembalikan $connection
kembali dari metode sehingga panggilan metode lainnya gagal lakukan ini:
public function db_connect() {
$connection = mysqli_connect(self::$db_host, self::$db_user, self::$db_pass, self::$db_name) or die("Error " . mysqli_error($connection));
echo "Conexión realizada". "<br>";
return $connection; // return the $connection object
}
Seperti yang disebutkan, kode Anda tidak efisien karena untuk setiap kueri yang dilakukan, kode (kembali) terhubung ke DB. Ini tidak perlu mahal/tidak efisien.
Ada banyak pendekatan untuk menyelesaikan ini.
- Hubungkan ke DB pada instantiasi kelas DB
misalnya
class Db{
private static $db_host = "localhost";
private static $db_user = "root";
private static $db_pass = "";
private static $db_name = "sivi";
public $connection;
public function __construct()
{
$this->connection = $this->db_connect();
}
public function db_connect() {
$connection = mysqli_connect(self::$db_host, self::$db_user, self::$db_pass, self::$db_name) or die("Error " . mysqli_error($connection));
echo "Conexión realizada". "<br>";
return $connection;
}
}
- Koneksi lambat, yaitu hanya terhubung pada kueri yang dijalankan pertama kali
misalnya
class Db{
private static $db_host = "localhost";
private static $db_user = "root";
private static $db_pass = "";
private static $db_name = "sivi";
public $connection = null;
public function __construct()
{
}
public function db_connect() {
$connection = mysqli_connect(self::$db_host, self::$db_user, self::$db_pass, self::$db_name) or die("Error " . mysqli_error($connection));
echo "Conexión realizada". "<br>";
return $connection;
}
public function db_query($query){
if ( null ==== $this->connection ) $this->connection = $this->db_connect();
var_dump($query);
$result = $this->connection->query($query);
while($row = mysqli_fetch_array($result)) {
echo $row["COD_PRE"] . "<br>";
}
}
}