DPTW/PHP/DPTW.MySQL.php

86 lines
3.3 KiB
PHP
Raw Normal View History

<?php
namespace DPTW;
class MySQL{
public $dptw;
private $connection = null;
private $inputs;
public function __construct($dptw, $inputs = null){
$this->dptw = $dptw;
$this->inputs = $inputs;
}
public static function process_query($query){
$subquery = "";
preg_replace_callback('/(, |\()\@([a-z0-9_]+)/i', function($values) use(&$subquery){
$subquery .= ($subquery ? ", " : "") . "@" . $values[2] . " as `" . $values[2] . "`";
}, $query);
return preg_replace('/;+$/', "", $query) . ($subquery ? ";select " . $subquery . ";" : "");
}
public static function variable_type($value){
return $value;
}
public function query($query, $variables = []){
$error = 0;
$results = null;
if(!$this->connection){
try{
$this->connection = new \PDO(\DPTW::string_variables($this->dptw->settings(["mysql_string_connection", "string_connection"]), [
"engine" => $this->dptw->settings(["mysql_engine", "engine"], $this->inputs),
"database" => $this->dptw->settings(["mysql_database", "database"], $this->inputs),
"host" => $this->dptw->settings(["mysql_host", "host"], $this->inputs),
"port" => $this->dptw->settings(["mysql_port", "port"], $this->inputs)
]), $this->dptw->settings(["mysql_user", "user"], $this->inputs), $this->dptw->settings(["mysql_password", "password"], $this->inputs));
}catch(Exception $exception){
$error |= 1 << 0;
};
};
if(!($error |= $this->connection ? 0 : 1 << 1)){
$query_processed = \DPTW::string_variables(self::process_query($query), array_merge($variables, [
"session" => "'" . ($this->dptw->session_get() ?? "null") . ":" . (\DPTW::get_ip() ?? "null") . ":" . $_SERVER["HTTP_USER_AGENT"] . "'"
]));
// print_r($query_processed);
($statement = $this->connection->prepare($query_processed))->execute();
do{
try{
$table = [];
$fetch_all = $statement->fetchAll(\PDO::FETCH_ASSOC);
foreach($statement->rowCount() == 0 ? [] : $fetch_all as $new_row){
$row = [];
foreach($new_row as $key => $value){
$row[$key] = self::variable_type($value);
};
$table[] = $row;
};
$results["tables"][] = $table;
}catch(\Exception $exception){};
}while($statement->nextRowset());
if(preg_match('/(,\s+?|\()\@/', $query)){
$l = count($results["tables"]) - 1;
foreach($results["tables"][$l][0] as $key => $value)
$results["variables"][$key] = self::variable_type($value);
unset($results["tables"][$l]);
};
};
return [$results, $error];
}
}