Currently, my website runs procedural PHP. I would like to achieve to have a database class that can be used for other classes.
STATUS QUO:
On every page I include my dp.php before my header.php, the content and footer.php appear. My db.php looks like this:
// Credentials
$dbhost = "localhost";
$dbname = "dbname";
$dbuser = "dbuser";
$dbpass = "dbpassword";
// Connection
global $db;
$db = new mysqli();
$db->connect($dbhost, $dbuser, $dbpass, $dbname);
$db->set_charset("utf8");
// Check Connection
if ($db->connect_errno) {
printf("Connect failed: %s\n", $db->connect_error);
exit();
}
GOAL:
Having a database object that I can integrate into the EventData class that I have been building. The desired function of this class is that it will allow me to easily access data of my events table on any page. My EventData-class.php looks like this:
Class EventData {
private $_db;
private $_event_id;
public function __construct($eventID) {
$this -> _event_id = $eventID;
}
public function getValue($fieldname) {
// Build query for getting event details
$query = 'SELECT * FROM events WHERE id=' . $this -> _event_id . '';
// Do Search
$results = $db->query($query);
// Store all event details available in variables
while ($result = $results->fetch_assoc()) {
$value = $result[$fieldname];
}
// Return value
return $value;
}
}
I am new to OOP and am interested in learning how I need to modify both db.php and EventData-class.php in order to work.