CustomerRewardsRESTAPI/Model/Database.php
2024-05-02 16:00:15 -05:00

124 lines
3.6 KiB
PHP

<?php
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
*/
/**
* Description of Database
*
* @author SCTN4
*/
class Database {
protected $connection = null;
public function __construct()
{
try {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$this->connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
if ( mysqli_connect_errno()) {
throw new Exception("Could not connect to database.");
}
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
public function processQuery($query = "", $params = [])
{
try {
$stmt = $this->executeQuery( $query, $params );
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
return $result;
} catch(Exception $e) {
throw New Exception( $e->getMessage() );
}
return false;
}
private function executeQuery($query = "" , $params = [])
{
try {
$stmt = $this->connection->prepare( $query );
if($stmt === false) {
throw New Exception("Unable to do prepared statement: " . $query);
}
if( $params ) {
$stmt->bind_param($params[0], $params[1]);
}
$stmt->execute();
return $stmt;
} catch(Exception $e) {
throw New Exception( $e->getMessage());
}
}
public function processStatement($query = "", $params = [])
{
try {
$keys = array_keys($params);
$n = count($params);
$query .= " (" . $params[$keys[0]] . ", ";
for($i = 1; $i < $n-1; $i++) {
$query .= "'" . $params[$keys[$i]] . "', ";
}
$query .= $params[$keys[$i]] . ")";
//Prepare the statement
$stmt = $this->connection->stmt_init();
$stmt = $this->connection->prepare($query);
if($stmt === false) {
throw New Exception("Unable to prepare the statement: " . $query);
}
$result = $stmt->execute();
if($result === false) {
throw New Exception("Unable to execute the statement.");
}
$rowCount = $this->connection->affected_rows;
if($rowCount < 1)
{
throw New Exception("Statement did not return any rows: " . $query);
}
$stmt->close();
return $rowCount;
} catch(Exception $e) {
throw New Exception( $e->getMessage() );
}
return false;
}
private function executeStatement(&$stmt)
{
try {
return var_dump($stmt);
$result = $stmt->execute();
if($result === false) {
throw New Exception("Unable to execute the statement.");
}
$rowCount = $this->connection->affected_rows;
return $rowCount;
} catch(Exception $e) {
throw New Exception( $e->getMessage() );
}
}
private function initStatement()
{
$statement = mysqli_stmt_init($this->connection);
return $statement;
}
private function prepareStatement($statement, $querystring)
{
}
}