標籤:
class mysql{ private $conn; //私人化 變數$conn private $db_host; //主機 private $db_user; private $db_password; private $db_name; //資料庫名稱 function __construct($db_host,$db_user,$db_password,$db_name){ //建構函式,傳入 類中的connect函數中 $this->db_host = $db_host; $this->db_user = $db_user; $this->db_password = $db_password; $this->db_name = $db_name; $this->connect(); } function connect(){ //資料庫連接函數 $this->conn = mysql_connect($this->db_host,$this->db_user,$this->db_password) or die("資料庫連接失敗".mysql_errno().":".mysql_error()); mysql_select_db($this->db_name,$this->conn) or die(‘開啟資料庫失敗‘).mysql_error(); mysql_set_charset(‘utf8‘); return $this->conn; } //插入資料庫,$table(資料庫名稱),$array function insert($table,$array){ $keys = "`".implode("`,`", array_keys($array))."`"; //調取數組中的索引值 $vals = "‘".implode("‘,‘", array_values($array))."‘"; //調去數組中的數值 $sql = "insert into {$table} ({$keys}) values({$vals})"; $query = mysql_query($sql); return mysql_insert_id(); } //刪除指定資料 function delete($table,$id,$where=null){ //語句: delete from table where id = .... $where = $where ==null?null:‘where ‘.$where; $sql = "delete from {$table} where id = {$id} limit 1"; $query = mysql_query($sql); return $query; } //選擇資料庫 public function select($table,$array,$where=null){ //語句: select * from table where `user`=‘$user‘...... foreach ($array as $key => $value) { $select[] = ‘`‘.$key.‘`=‘.$value; } $select = implode(‘ and ‘, $select); $where = $where == null?null:$where; $sql = "select * from {$table} where ".$select.‘ ‘.$where; return $sql; } //修改資料庫 function update($table,$array,$where = null){ //語句: update table set `name`=‘kopa‘ where id = .... foreach ($array as $key => $value) { $string[] = ‘`‘.$key.‘`=‘.$value; } $string =implode(‘`,‘,$string); $where = $where==null?null:" where ".$where; $sql = "update {$table} set ".$string.$where; return $sql; // $query = mysql_query($sql); // return $query; // print_r("update {$table} set ".$string.$where); } //讀取資料庫總行數 mysql_num_row function totalRow($sql){ $query = mysql_query($sql); $result = mysql_num_rows($query); return $result; } //讀取資料庫的數組 function fetch_array($sql){ $query = mysql_query($sql); $res = mysql_fetch_array($query); return $res; }}$db = new mysql("localhost",‘root‘,‘3363064‘,‘ctxy‘);
[我在學php之三]Po上自己寫的資料庫類,方便以後進行尋找。