tweetmonitor/includes/classes/class.Database.php
2016-02-09 14:23:43 +01:00

247 lines
3.4 KiB
PHP

<?php
/**
* MySQL Wrapper Class in PHP5
*/
class Database
{
private $queryResult;
private $queryType;
private $lastInsertId;
public function __construct()
{
$queryResult = '';
$queryType = '';
$lastInsertId = '';
}
public function executeQuery($sql = '')
{
try
{
if (!empty($sql))
{
$this->runQuery($sql);
return $this;
}
else
{
trigger_error('You need to provide a query.', E_USER_ERROR);
}
}
catch(exception $e)
{
return $e;
}
}
private function runQuery($query = NULL)
{
try
{
if (!is_null($query))
{
$this->queryType = $this->getQueryType($query);
if (!$this->queryResult = mysql_query($query))
{
trigger_error('Error in SQL query.', E_USER_ERROR);
}
if ($this->queryType == 'INSERT')
{
$this->lastInsertId = mysql_insert_id();
}
}
}
catch(exception $e)
{
return $e;
}
}
public function getLastInsertId()
{
return $this->lastInsertId;
}
private function freeResult()
{
return mysql_free_result($this->queryResult);
}
private function getQueryType($query = '')
{
$query = explode(' ', $query);
return strtoupper($query[0]);
}
public function querySucceeded()
{
if (!$this->queryResult)
{
return FALSE;
}
else
{
return TRUE;
}
}
public function getAffectedRows()
{
try
{
if ($this->querySucceeded())
{
if (($this->queryType == 'SELECT') || ($this->queryType == 'SHOW'))
{
return mysql_num_rows($this->queryResult);
}
else
{
return mysql_affected_rows();
}
}
else
{
return 0;
}
}
catch(exception $e)
{
return $e;
}
}
public function wasInserted()
{
try
{
if ($this->queryType == 'INSERT' && $this->querySucceeded())
{
return $this->getLastInsertId();
}
else {
return FALSE;
}
}
catch(exception $e)
{
return $e;
}
}
public function wasUpdated()
{
try
{
if ($this->queryType == 'UPDATE' && $this->querySucceeded()) {
return TRUE;
}
else {
return FALSE;
}
}
catch(exception $e)
{
return $e;
}
}
public function wasDeleted()
{
try
{
if ($this->queryType == 'DELETE' && $this->querySucceeded())
{
return TRUE;
}
else {
return FALSE;
}
}
catch(exception $e)
{
return $e;
}
}
public function asArray()
{
try
{
if (!$this->queryResult)
{
return FALSE;
}
else
{
if (!$this->getAffectedRows() == 0)
{
$rows = array();
while ($row = mysql_fetch_assoc($this->queryResult))
{
array_push($rows, $row);
}
$this->freeResult();
return $rows;
}
else
{
return FALSE;
}
}
}
catch(exception $e)
{
return $e;
}
}
public function asObject()
{
try
{
if (!$this->queryResult)
{
return FALSE;
}
else
{
if (!$this->getAffectedRows() == 0)
{
$rows = array();
while ($row = mysql_fetch_object($this->queryResult))
{
array_push($rows, $row);
}
$this->freeResult();
return $rows;
}
else
{
return FALSE;
}
}
}
catch(exception $e)
{
return $e;
}
}
public function clean($str)
{
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
}
?>