Jouw methode:
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>";
}
stemt de $connection
niet opnieuw af terug van de methode zodat de restmethode-aanroepen mislukken, doe dit:
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
}
Zoals vermeld, is uw code niet efficiënt omdat voor elke uitgevoerde query de code (opnieuw) verbinding maakt met de DB. Dit is onnodig duur/inefficiënt.
Er zijn veel manieren om dit op te lossen.
- Maak verbinding met de DB op de instantie van de DB-klasse
bijv.
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;
}
}
- Luie verbinding, d.w.z. alleen verbinding maken bij de eerste uitgevoerde zoekopdracht
bijv.
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>";
}
}
}