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:
You have to use $this
to access properties of the own class.
$this->connection = ....
$result = $this->connection->...
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
connection = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name)
or die("Error " . mysqli_error($this->connection));
}
public function db_query($query) {
var_dump($query);
$result = $this->connection->query($query);
while ($row = mysqli_fetch_array($result)) {
echo $row["COD_PRE"] . "
";
}
}
}
$con = new Db();
$con->db_query('SELECT `COD_PRE`, `CODE` FROM `test` WHERE `CODE` = 457 AND CONFIN = 1');
?>
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.