I\'m trying to write this class to connect and query my database, but I got this error:
Fatal error: Call to a member function query() on null in C:
Your method:
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". "
";
}
does not retun the $connection
back from the method so the rest method calls fail do this:
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". "
";
return $connection; // return the $connection object
}
As mentioned, your code is not efficient since for every query performed the code (re-)connects to the DB. THis is unnecessarily expensive/inefficient.
There are many approaches to solve this.
e.g
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". "
";
return $connection;
}
}
e.g
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". "
";
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"] . "
";
}
}
}