Kelas operasi pangkalan data
Buat kelas sambungan pangkalan data baharu MysqlDatabase.class.php
1, sifat diperlukan untuk sambungan pangkalan data
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/3/3 0003 * Time: 下午 2:57 */ class MysqlDatabase{ //數(shù)據(jù)庫連接信息 private $dbConfig=array( 'host'=>'localhost', 'port'=>'3306', 'user'=>'root', 'pwd'=>'root', 'charset'=>'utf8', 'dbname'=>'php', ); //數(shù)據(jù)庫連接資源 private $link; }
2, pemulaan2, pemulaan
, Bilangan sambungan ke pangkalan data
<?php private function initAttr($params){ //初始化屬性 $this->dbConfig=array_merge($this->dbConfig,$params); }
4, Mesej ralat paparan pangkalan data pertanyaan
<?php //獲取數(shù)據(jù)庫連接 private function connectServer(){ $host=$this->dbConfig['host']; $port=$this->dbConfig['port']; $user=$this->dbConfig['user']; $pwd=$this->dbConfig['pwd']; //連接數(shù)據(jù)庫服務(wù)器 if ($link=mysql_connect("$host:$port",$user,$pwd)){ $this->link=$link; }else{ die('數(shù)據(jù)庫連接失敗,請確認(rèn)信息!'.mysql_error()); } }
5, Tetapkan set aksara
<?php //查詢數(shù)據(jù)庫顯示錯誤信息 function query($sql){ if($result=mysql_query($sql)){ //執(zhí)行成功 return $result; }else{ //執(zhí)行失敗,顯示錯誤信息以便于調(diào)試程序 echo 'sql執(zhí)行失敗:<br>'; echo '錯誤的sql為:',$sql,'<br>'; echo '錯誤的代碼為:',mysql_errno(),'<br>'; echo '錯誤的信息為:',mysql_error(),'<br>'; die(); } }
<?php
//設(shè)定連接字符集
private function setCharset(){
$sql="set names {$this->dbConfig['charset']}";
$this->query($sql);
}
parameter binaan 7, Pertanyaan sekeping data Dan kembalikan set hasil
<?php //構(gòu)造方法 public function __construct($params=array()) { //初始化屬性 $this->initAttr($params); //連接數(shù)數(shù)據(jù)庫 $this->connectServer(); //設(shè)定字符集 $this->setCharset(); }8, tanya semua data dan kembalikan set hasil
<?php //查詢單條數(shù)據(jù)并返回結(jié)果集 function fetchRow($sql){ //執(zhí)行query()函數(shù) if($result=query($sql)){ //從結(jié)果集取得依次數(shù)據(jù)即可 $row=mysql_fetch_array($result,MYSQL_ASSOC); return $row; }else{ return false; } }9, paparan kod keseluruhan:
<?php //查詢所有數(shù)據(jù)并返回結(jié)果集 function fetchAll($sql){ //執(zhí)行query()函數(shù) if($result=query($sql)){ //執(zhí)行成功 //遍歷結(jié)果集 $rows=array(); while($row=mysql_fetch_array($result,MYSQL_ASSOC)){ $rows[]=$row; } //釋放結(jié)果集資源 mysql_free_result($result); return $rows; }else{ //執(zhí)行失敗 return false; } }