Created
July 9, 2021 02:16
-
-
Save SpiffGreen/72caa0c4ee3d3fa14734ad84d066e7e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Spiff Jekey-Green ([email protected]) | |
* @copyright MIT | |
*/ | |
class DB { | |
public $db_host; | |
public $db_user; | |
public $db_pass; | |
public $db_name; | |
public $conn; | |
public function __construct($host, $user, $pass, $name) { | |
$this->db_host = $host; | |
$this->db_user = $user; | |
$this->db_pass = $pass; | |
$this->db_name = $name; | |
} | |
public function __destruct() { | |
if($this-conn !== NULL) { | |
mysqli_close($this->conn); | |
} | |
} | |
public function connect() { | |
$this->conn = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name); | |
if($this->conn->connect_errno) { | |
return NULL; | |
} | |
return $this->conn; | |
} | |
public function query($stm, $val = []) { | |
$pattern = '/\?/'; | |
preg_match_all($pattern, $stm, $matches, PREG_SET_ORDER); | |
if(count($val) == 0 || count($matches) == 0) { | |
$result = $this->conn->query($stm); | |
$rows = $result->fetch_all(MYSQLI_ASSOC); | |
return $rows; | |
} | |
// Do the main logic here | |
$type_str = ""; | |
foreach($val as $item) { | |
switch(gettype($item)) { | |
case "string": | |
$type_str .= "s"; | |
break; | |
case "integer": | |
$type_str .= "i"; | |
break; | |
case "double": | |
$type_str .= "d"; | |
break; | |
} | |
} | |
$prepared_stm = $this->conn->prepare($stm); | |
$prepared_stm->bind_param($type_str, ...$val); | |
$prepared_stm->execute(); | |
$result = $prepared_stm->get_result(); | |
if(gettype($result) === "boolean") { | |
// print_r($prepared_stm); | |
$result = array( | |
"affected_rows" => $prepared_stm->affected_rows, | |
"id" => $prepared_stm->id, | |
"error" => $prepared_stm->error, | |
"errno" => $prepared_stm->errno | |
); | |
} | |
else { | |
$result = $result->fetch_all(MYSQLI_ASSOC); | |
} | |
return $result; | |
} | |
} | |
$db = new DB("DB_HOST", "DB_USER", "PASSWORD", "TABLE_NAME"); | |
if($connection = $db->connect()) { | |
echo "Connection Successfull\n"; | |
} | |
// DB operations | |
// $result = $db->query("SELECT * FROM users WHERE id = ?", [14]); | |
// $result = $db->query("INSERT INTO users (name, email, password) VALUES (?, ?, ?)", ["John Doe", "[email protected]", "superstrongpassword"]); | |
// $result = $db->query("UPDATE users SET password = ? WHERE email = ?", ["anMD5Hash", "[email protected]"]); | |
// $result = $db->query("DELETE FROM users WHERE id = ?", [23]); | |
// print_r($result); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment