I have been using a static class to connect and retrieve information from a MySQL database and also reading about how static works in php. I'm still not sure if the code is bad or not and why (besides the usual static are dangerous). Also, code improvements suggestions will be appreciated.
class Database {
const STOREDPROCEDURE = 1;
const ADHOC = 2;
private static $instance;
private static function call() {
if (!isset(self::$instance)) {
self::$instance = new MySQLi('localhost', 'root', '', 'alfred');
if (self::$instance -> connect_error) throw new Exception(self::$instance -> connect_error);
self::$instance -> set_charset('utf8');
}
return self::$instance;
}
public static function query() {
//
$arguments = func_get_args();
$count = count($arguments);
//
$references = array();
for ($i = 2; $i <= count($arguments) - 1; $i++) $references[$i] = &$arguments[$i];
//
$query = $count === 0 ? '' : str_repeat('?, ', $count - 4) . '?';
$query = 'CALL' . ' ' . $arguments[1] . '(' . $query . ');';
//
$stmt = self::call() -> prepare($query);
if ($count > 2) call_user_func_array(array($stmt, 'bind_param'), $references);
//
$stmt -> execute();
$stmt -> store_result();
//
$result = array();
while ($metadata = $stmt -> result_metadata()) {
//
$fields = array();
foreach ($metadata -> fetch_fields() as $field) {
$reference[$field -> name] = '';
$fields[$field -> name] = &$reference[$field -> name];
}
//
call_user_func_array(array($stmt, 'bind_result'), $fields);
//
$rows = array();
while ($stmt -> fetch()) {
$row = new stdClass();
foreach ($fields as $name => $value) $row -> $name = $value;
array_push($rows, $row);
}
//
array_push($result, empty($rows) ? null : $rows);
//
$stmt -> next_result();
}
//
$stmt -> free_result();
$stmt -> close();
//
return $result;
}
}
You can use the code by doing:
$response = Database::query(
Database::STOREDPROCEDURE,
'UserRead',
'sss',
$useremail,
$userpassword,
$userhash
);