I am just creating a simple standalone stock updater and turning my hand to OOP rather than just function based. I have created a simple class that requires my database connection but want to know the best practice for including and using the database connection. The first exert is the class that will be using the database. The second is the contents of 'dbconnector.php'.
class stockUpdater {
var $data = '';
function __construct() {
include('dbconnector.php');
print_r($mysqli);
//check and get file
$fp = fopen('stockfiles/stockfile.csv', 'r');
if($fp){
while(! feof($fp)) {
$prods[] = fgetcsv($fp);
}
}
if(empty($prods)){
$this->logError(time(),'No data found in file');
}
}
//error logging function
private function logError($time, $message){
}
}
$updateStock = new stockUpdater();
I Know what I'm doing here works but dont know if there's a better way of doing it than including the database connection script in every class as this could create multiple db connections when only 1 is needed.
$mysqli = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}