Skip to content

Instantly share code, notes, and snippets.

@JamesCullum
Created October 16, 2022 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesCullum/5b6363fc640bf0d2723dc698e59e2b69 to your computer and use it in GitHub Desktop.
Save JamesCullum/5b6363fc640bf0d2723dc698e59e2b69 to your computer and use it in GitHub Desktop.
Helper class and method to easily use PHP prepared statements (using PHP 8.1.0+)
<?php
// Helper for prepared statements using main connection in global variable $db
// Class is used, so that we can use __destruct to close connections automatically
class PSQLWrapper {
private $stmt;
private $query_type;
public function __construct($query, $vars = false) {
global $db;
$check_type = ["SELECT", "INSERT", "UPDATE", "DELETE"];
$query_extract = strtoupper(explode(" ", $query)[0]);
if(!in_array($query_extract, $check_type)) throw new Exception("Unknown query type");
$this->query_type = $query_extract;
$this->stmt = $db->prepare($query);
if(!$this->stmt) throw new Exception("Invalid query");
if($vars !== false) $this->run($vars);
}
public function __destruct() {
$this->close();
}
public function close() {
if($this->stmt === null) return false;
$this->stmt->close();
$this->stmt = null;
return true;
}
public function run($vars) {
if(!is_array($vars)) $vars = [$vars];
$this->stmt->execute($vars);
}
public function get_result($mode = MYSQLI_ASSOC) {
if(in_array($this->query_type, ["INSERT", "UPDATE", "DELETE"])) {
return $this->stmt->affected_rows;
}
$result = $this->stmt->get_result();
if(!$result) return false;
$data = array();
while ($row = $result->fetch_array($mode)) {
$data[] = $row;
}
return $data;
}
}
// Shorthand method
function pquery($query, $vars = null) {
$wrapper = new PSQLWrapper($query, $vars);
$result = $wrapper->get_result();
$wrapper->close();
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment