78 lines
2.4 KiB
PHP
78 lines
2.4 KiB
PHP
<?php
|
|
|
|
class Database {
|
|
|
|
private $conn;
|
|
|
|
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 = []) {
|
|
// Prepare the SQL query
|
|
if ($stmt = $this->conn->prepare($query)) {
|
|
// Bind parameters to the prepared statement (if any)
|
|
if (!empty($params)) {
|
|
$types = str_repeat('s', count($params)); // Assuming all params are strings
|
|
$stmt->bind_param($types, ...$params);
|
|
}
|
|
|
|
// Execute the statement
|
|
if (!$stmt->execute()) {
|
|
throw new Exception("Query execution failed: " . $stmt->error);
|
|
}
|
|
|
|
// Return the statement result
|
|
return $stmt;
|
|
} else {
|
|
throw new Exception("Query preparation failed: " . $this->conn->error);
|
|
}
|
|
}
|
|
|
|
public function getRow($query, $params = []) {
|
|
try {
|
|
// Perform the query using prepared statement
|
|
$stmt = $this->query($query, $params);
|
|
|
|
// Get the result of the query
|
|
$result = $stmt->get_result();
|
|
|
|
// Fetch the first row from the result
|
|
return $result->fetch_assoc();
|
|
} catch (Exception $e) {
|
|
// Handle the exception (log it, display a message, etc.)
|
|
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();
|
|
}
|
|
} |