Skip to content

Instantly share code, notes, and snippets.

@f
Created February 1, 2011 12:00
Show Gist options
  • Save f/805764 to your computer and use it in GitHub Desktop.
Save f/805764 to your computer and use it in GitHub Desktop.
<?php
class MySQL {
private static $_instance = NULL;
private $conn = NULL;
public $server;
public $username;
public $password;
public $db_name;
/**
* @static
* @return MySQL
*/
public static function getInstance()
{
if (self::$_instance == NULL)
self::$_instance = new self();
return self::$_instance;
}
public function connect()
{
$this->conn = @mysql_connect($this->server,$this->username,$this->password);
if (!is_resource($this->conn))
throw new Exception("Database Connection Error.");
mysql_select_db($this->db_name,$this->conn);
mysql_query("SET NAMES 'UTF8'",$this->conn);
}
public function __destruct()
{
@mysql_close($this->conn);
}
private function createSql($sql, $parameters)
{
return vsprintf($sql, $parameters);
}
public function query($sql)
{
$result = @mysql_query($sql,$this->conn);
if (!$result)
throw new Exception('MySQL Query Error - ['.mysql_error($this->conn).'] SQL: {{ '.$sql.' }}');
return $result;
}
public function affectedRowNumber()
{
return mysql_affected_rows($this->conn);
}
public function insertId()
{
return mysql_insert_id($this->conn);
}
public function getRows($sql)
{
if (!preg_match('{^(SELECT|SHOW)}ui',$sql))
{
throw new Exception('Wrong method called - SQL: {{ '.$sql.' }}');
return false;
}
$resultArray = array();
$result = $this->query($sql);
while (false!==($row = mysql_fetch_assoc($result)))
{
array_push($resultArray,$row);
}
return $resultArray;
}
public function getFirstRow($sql)
{
$parameters = func_get_args();
array_shift($parameters);
$sql = $this->createSql($sql, $parameters);
$rows = $this->getRows($sql);
if (count($rows) > 0)
return $rows[0];
else
return false;
//return false dönebilir çünkü en fazla 1 sonuç dönecek.
}
public function clear($str)
{
return addcslashes(stripslashes(trim($str)), "\x00\x1a\x22\x27\n\r");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment