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:\xxxxxx\xxxx\xxxxx\xxxxxxx\pages\config\class.php on line 24
Php Code:
<?php
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 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>";
}
public function db_query($query){
$connection = $this->db_connect();
var_dump($query);
$result = $connection->query($query);
while($row = mysqli_fetch_array($result)) {
echo $row["COD_PRE"] . "<br>";
}
}
}
$con = new Db();
$con->db_query('SELECT `COD_PRE`, `CODE` FROM `test` WHERE `CODE` = 457 AND CONFIN = 1');
?>
You have to use
$this
to access properties of the own class.It would be better if you used a constructor to initiate the connection, currently you are opening a new connection to the database every time you use the query method.
edit: Your class could look like this
I see no need for the properties to be static, so I changed them too.
The db_query method is in my opinion too unflexible, as it directly outputs your result. I would use fetch_all to return the whole resultset as an array. That way you can freely choose how you want to handle your results.
Your method:
does not retun the
$connection
back from the method so the rest method calls fail do this: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
e.g