CustomerRewardsRESTAPI/Model/Database.php
2024-05-29 14:47:51 -05:00

116 lines
3.7 KiB
PHP

<?php
/**
* Description of Database
*
* @author Mike Howard
*/
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->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();
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
return $result;
} catch(Exception $e) {
throw New Exception( $e->getMessage() );
}
return false;
}
public function processStatement($query = "")
{
try {
//Prepare the statement
$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: " . $query);
}
$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;
}
public function processImage($query, $imageModel) {
try
{
/*if($this->connection == null)
{
$this->connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
}*/
$data = $this->connection->real_escape_string($imageModel->imageBlob);
$result = $this->connection->query($query."(".$imageModel->memberId.", '".$imageModel->imageType."', '".$data."')");
if($result === false) {
$msg = "Unable to execute the statement: " . $query;
return $this->unprocessableQueryResponse($msg);
}
$rowCount = $this->connection->affected_rows;
if($rowCount < 1)
{
$msg = "Statement did not return any rows: " . $query;
return $this->unprocessableQueryResponse($msg);
}
} catch(Exception $e) {
$msg = $query . " " . $e->getMessage();
return $this->unprocessableQueryResponse($msg);
}
$this->connection->close();
return $rowCount;
}
private function unprocessableQueryResponse($msg)
{
$response['status_code_header'] = 'HTTP/1.1 422 Unprocessable Query';
$response['body'] = json_encode([
'error' => 'Invalid query'
]);
$this->strErrorDesc = 'Unprocessable Query';
$this->strErrorHeader = 'HTTP/1.1 422 Unprocessable Query';
$this->strErrorMessage = $msg;
return $response;
}
}