Reputation: 73221
I'm playing around with classes in php and just can't find the right way to do so.
I have the following class:
class db_connection {
private $dbc;
public function __construct()
{
$this->dbc = new mysqli(HOST_ONE, USER_ONE, PASS_ONE, DB_ONE) or die ($this->dbc->error);
}
public function getDbc()
{
return $this->dbc;
}
}
and try to run it like this:
$db = new db_connection();
$db->getDbc();
// TESTQUERY
$abfrage = "SELECT * FROM databases";
$result = $db->query($abfrage);
while ($row = $result->fetch_assoc()) {
echo $row['id'];
}
HOST_ONE and so on are set, I don't get any error messages though I have error_reporting( E_ALL );
enabled
I tried it in many different ways, but none of them is working...
Can someone push me in the right direction on how to use this simple class?
Upvotes: 0
Views: 246
Reputation: 43441
You should use code like this:
$dbClass = new db_connection();
$db = $dbClass->getDbc();
$db->query("SELECT * FROM databases");
$dbClass = new db_connection();
creates connection and returns db_connection
class instance to $dbClass
. Now that you have connected to database, use $db = $dbClass->getDbc();
to get connection object itself and do any database related actions with it.
Upvotes: 1
Reputation: 311
I think you should use it like:
$db_con = new db_connection();
$db = $db_con->getDbc();
The function getDbc() returns the object you need. As so you have to send it to $db variable, to get it. Executing the method does not attribute its value to "self"($db_con) but returns a value.
Upvotes: 2