Din metode:
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>";
}
genindstiller ikke $connection
tilbage fra metoden, så resten metodekald mislykkes gør dette:
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
}
Som nævnt er din kode ikke effektiv, da for hver forespørgsel, der udføres, forbinder koden (gen-) til DB'en. Det er unødvendigt dyrt/ineffektivt.
Der er mange tilgange til at løse dette.
- Opret forbindelse til DB'en ved instansieringen af DB-klassen
f.eks.
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;
}
}
- Doven forbindelse, dvs. opret forbindelse kun ved første udførte forespørgsel
f.eks.
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>";
}
}
}