<?php
class DB {
Public $conn;
public static $sql;
Public static $instance =null;
Private Function __construct () {
require_once (' db.config.php ');
$this->conn = mysql_connect ($db [' Host '], $db [' User '], $db [' Password '];
if (!mysql_select_db ($db [' database '], $this->conn)) {
echo "Failure";
};
mysql_query (' Set names UTF8 ', $this->conn);
}
Public static function getinstance () {
if (Is_null (self:: $instance)) {
Self :: $instance = new db;
}
return self:: $instance;
}
/**
* Query Database
*/
Public function Select ($table, $condition =array (), $field = Array ()) {
$where = ";
if (!empty ($condition)) {
foreach ($condition as $k = = $v) {
$where. = $k. " = ' ". $v." ' and ";
}
$where = ' where '. $where. ' 1=1 ';
}
$fieldstr = ";
if (!empty ($field)) {
foreach ($field as $k = = $v) {
$fieldstr. = $v. ', ';
}
$fieldstr = RTrim ($fieldstr, ', ');
}else{
$fieldstr = ' * ';
}
Self :: $sql = ' Select {$fieldstr} from {$table} {$where} ';
$result =mysql_query (self:: $sql, $this->conn);
$resuleRow = Array ();
$i = 0;
While ($row =mysql_fetch_assoc ($result)) {
foreach ($row as $k = = $v) {
$resuleRow [$i] [$k] = $v;
}
$i + +;
}
return $resuleRow;
}
/**
* Add a record
*/
Public function Insert ($table, $data) {
$values = ";
$datas = ";
foreach ($data as $k = = $v) {
$values. = $k. ', ';
$datas. = "' $v '". ', ';
}
$values = RTrim ($values, ', ');
$datas = RTrim ($datas, ', ');
Self :: $sql = ' INSERT into {$table} ({$values}) VALUES ({$datas}) ";
if (mysql_query (self:: $sql)) {
return mysql_insert_id ();
}else{
return false;
};
}
/**
* Modify a record
*/
Public function Update ($table, $data, $condition =array ()) {
$where = ";
if (!empty ($condition)) {
foreach ($condition as $k = = $v) {
$where. = $k. " = ' ". $v." ' and ";
}
$where = ' where '. $where. ' 1=1 ';
}
$updatastr = ";
if (!empty ($data)) {
foreach ($data as $k = = $v) {
$updatastr. = $k. " = ' ". $v." ', ";
}
$updatastr = ' Set '. RTrim ($updatastr, ', ');
}
Self :: $sql = "Update {$table} {$updatastr} {$where}";
return mysql_query (self:: $sql);
}
/**
* Delete Records
*/
Public function Delete ($table, $condition) {
$where = ";
if (!empty ($condition)) {
foreach ($condition as $k = = $v) {
$where. = $k. " = ' ". $v." ' and ";
}
$where = ' where '. $where. ' 1=1 ';
}
Self :: $sql = "Delete from {$table} {$where}";
return mysql_query (self:: $sql);
}
Public static function Getlastsql () {
echo Self:: $sql;
}
}
$db = Db::getinstance ();
$list = $db->select (' demo ', Array (' name ' = ' tom ', ' password ' = ' ds '), Array (' name ', ' password '));
echo $db->insert (' demo ', Array (' name ' = ' recent you ', ' password ' = ' 123 '));
echo $db->update (' demo ', Array ("name" = ' xxx ', "password" = ' 123 '), array (' ID ' =>1));
echo $db->delete (' demo ', Array (' id ' = ' 2 '));
Db::getlastsql ();
echo "<pre>";
?>
PHP Single-instance mode