novaconium/src/Database.php

126 lines
3.7 KiB
PHP

<?php
class Database {
private $conn;
public $lastid;
public function __construct($dbinfo) {
$this->conn = new mysqli($dbinfo['host'], $dbinfo['user'], $dbinfo['pass'], $dbinfo['name']);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($query, $params = []) {
// Clean up pending results to avoid "commands out of sync"
while ($this->conn->more_results() && $this->conn->next_result()) {
if ($res = $this->conn->use_result()) {
$res->free();
}
}
// Prepare the SQL statement
$stmt = $this->conn->prepare($query);
if (!$stmt) {
throw new Exception("Query preparation failed: " . $this->conn->error);
}
// Bind parameters if needed
if (!empty($params)) {
$types = str_repeat('s', count($params)); // Use 's' for all types, or detect types dynamically
$stmt->bind_param($types, ...$params);
}
// Execute the statement
if (!$stmt->execute()) {
$stmt->close();
throw new Exception("Query execution failed: " . $stmt->error);
}
// Save last insert id if it's an INSERT query
if (preg_match('/^\s*INSERT/i', $query)) {
$this->lastid = $this->conn->insert_id;
} else {
$this->lastid = 0;
}
// Decide what to return
// For SELECT/SHOW etc., return result set
if (preg_match('/^\s*(SELECT|SHOW|DESCRIBE|EXPLAIN)/i', $query)) {
$result = $stmt->get_result();
$stmt->close();
return $result;
}
// For INSERT/UPDATE/DELETE, return success status
$success = $stmt->affected_rows;
$stmt->close();
return $success;
}
public function lastid() {
return $this->lastid;
}
public function getRow($query, $params = []) {
try {
// Prepare the SQL statement
$stmt = $this->conn->prepare($query);
if (!$stmt) {
throw new Exception("Query preparation failed: " . $this->conn->error);
}
// Bind parameters
if (!empty($params)) {
$types = str_repeat('s', count($params)); // You may improve this with actual type detection
$stmt->bind_param($types, ...$params);
}
// Execute the statement
if (!$stmt->execute()) {
$stmt->close();
throw new Exception("Query execution failed: " . $stmt->error);
}
// Get result
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->close();
return $row;
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
return null;
}
}
public function getRows($query, $params = []) {
$stmt = $this->conn->prepare($query);
if (!$stmt) {
die("Query preparation failed: " . $this->conn->error);
}
// Bind parameters if provided
if (!empty($params)) {
$types = str_repeat('s', count($params)); // Assuming all are strings, adjust as needed
$stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result(); // Requires MySQL Native Driver (mysqlnd)
if ($result) {
return $result->fetch_all(MYSQLI_ASSOC);
} else {
return [];
}
}
public function close() {
$this->conn->close();
}
}