Hey.
I created a Database System which should be very save.
Code:
Example:
Why should you use it?
- save querys
- multi-querys
- callbacks (query execute when callback returns boolean "true")
If u got a question just ask.
Cya
I created a Database System which should be very save.
Code:
Code:
class Database {
private $connection;
private $executedQuerys = [];
public function __construct(\mysqli $connection) {
$this->connection = $connection;
}
public function query($query, $params = [], $callback = null) {
$query = $this->getConvertedQueryString($query, $params);
if($callback == null || $callback() == true) {
$return = $this->connection->query($query) or die($this->connection->error);
} else {
return null;
}
$this->executedQuerys[] = [
'query' => $query,
'data' => $return
];
return $return;
}
public function multiQuery($querys = []) {
$result = [];
foreach($querys as $query) {
$qry = $query['query'];
$params = isset($query['params']) ? $query['params'] : [];
$callback = isset($query['callback']) ? $query['callback'] : null;
$result[] = $this->query($qry, $params, $callback);
}
return $result;
}
private function getConvertedQueryString($query, $params = []) {
$toFind = [];
$toReplace = [];
foreach($params as $key => $value) {
$toFind[] = ':'.$key;
$toReplace[] = "'".$this->connection->real_escape_string($value)."'";
}
$query = str_replace($toFind, $toReplace, $query);
return $query;
}
public function getExecutedQuerys() {
return $this->executedQuerys;
}
}
Code:
$db = new Database(new MySQLi('localhost', 'root', '', 'test'));
$user = $db->query('SELECT * FROM users WHERE username = :username AND id = :id', [
'username' => 'Test',
'id' => 1
], function() use ($db) {
return $db->query('SELECT * FROM users WHERE username = :username', ['username' => 'Test'])->num_rows == 0;
});
echo $multiQuery = $db->multiQuery([
[
'query' => 'SELECT * FROM users WHERE username = :username AND id = :id',
'params' => [
'username' => 'iExit',
'id' => 1
]
],
[
'query' => 'INSERT INTO users SET username = :username',
'params' => [
'username' => 'Test1231'
],
'callback' => function() use ($db) {
//callback :D
return $db->query('SELECT * FROM users WHERE username = :username', ['username' => 'Test1231'])->num_rows == 0;
}
]
])[0]->fetch_object()->username; // returns "iExit" :D
Why should you use it?
- save querys
- multi-querys
- callbacks (query execute when callback returns boolean "true")
If u got a question just ask.
Cya