當前位置:首頁 » 編程語言 » mysqlphp封裝類

mysqlphp封裝類

發布時間: 2022-06-14 15:14:33

1. 求個好用的php mysql封裝類

<?php


classMMysql{

protectedstatic$_dbh=null;//靜態屬性,所有資料庫實例共用,避免重復連接資料庫
protected$_dbType='mysql';
protected$_pconnect=true;//是否使用長連接
protected$_host='localhost';
protected$_port=3306;
protected$_user='root';
protected$_pass='root';
protected$_dbName=null;//資料庫名
protected$_sql=false;//最後一條sql語句
protected$_where='';
protected$_order='';
protected$_limit='';
protected$_field='*';
protected$_clear=0;//狀態,0表示查詢條件干凈,1表示查詢條件污染
protected$_trans=0;//事務指令數

/**
*初始化類
*@paramarray$conf資料庫配置
*/
publicfunction__construct(array$conf){
class_exists('PDO')ordie("PDO:classnotexists.");
$this->_host=$conf['host'];
$this->_port=$conf['port'];
$this->_user=$conf['user'];
$this->_pass=$conf['passwd'];
$this->_dbName=$conf['dbname'];
//連接資料庫
if(is_null(self::$_dbh)){
$this->_connect();
}
}

/**
*連接資料庫的方法
*/
protectedfunction_connect(){
$dsn=$this->_dbType.':host='.$this->_host.';port='.$this->_port.';dbname='.$this->_dbName;
$options=$this->_pconnect?array(PDO::ATTR_PERSISTENT=>true):array();
try{
$dbh=newPDO($dsn,$this->_user,$this->_pass,$options);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//設置如果sql語句執行錯誤則拋出異常,事務會自動回滾
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);//禁用preparedstatements的模擬效果(防SQL注入)
}catch(PDOException$e){
die('Connectionfailed:'.$e->getMessage());
}
$dbh->exec('SETNAMESutf8');
self::$_dbh=$dbh;
}

/**
*欄位和表名添加`符號
*保證指令中使用關鍵字不出錯針對mysql
*@paramstring$value
*@returnstring
*/
protectedfunction_addChar($value){
if('*'==$value||false!==strpos($value,'(')||false!==strpos($value,'.')||false!==strpos($value,'`')){
//如果包含*或者使用了sql方法則不作處理
}elseif(false===strpos($value,'`')){
$value='`'.trim($value).'`';
}
return$value;
}

/**
*取得數據表的欄位信息
*@paramstring$tbName表名
*@returnarray
*/
protectedfunction_tbFields($tbName){
$sql='SELECTCOLUMN_NAMEFROMINFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME="'.$tbName.'"ANDTABLE_SCHEMA="'.$this->_dbName.'"';
$stmt=self::$_dbh->prepare($sql);
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
$ret=array();
foreach($resultas$key=>$value){
$ret[$value['COLUMN_NAME']]=1;
}
return$ret;
}

/**
*過濾並格式化數據表欄位
*@paramstring$tbName數據表名
*@paramarray$dataPOST提交數據
*@returnarray$newdata
*/
protectedfunction_dataFormat($tbName,$data){
if(!is_array($data))returnarray();
$table_column=$this->_tbFields($tbName);
$ret=array();
foreach($dataas$key=>$val){
if(!is_scalar($val))continue;//值不是標量則跳過
if(array_key_exists($key,$table_column)){
$key=$this->_addChar($key);
if(is_int($val)){
$val=intval($val);
}elseif(is_float($val)){
$val=floatval($val);
}elseif(preg_match('/^(w*(+|-|*|/)?w*)$/i',$val)){
//支持在欄位的值裡面直接使用其它欄位,例如(score+1)(name)必須包含括弧
$val=$val;
}elseif(is_string($val)){
$val='"'.addslashes($val).'"';
}
$ret[$key]=$val;
}
}
return$ret;
}

/**
*執行查詢主要針對SELECT,SHOW等指令
*@paramstring$sqlsql指令
*@returnmixed
*/
protectedfunction_doQuery($sql=''){
$this->_sql=$sql;
$pdostmt=self::$_dbh->prepare($this->_sql);//prepare或者query返回一個PDOStatement
$pdostmt->execute();
$result=$pdostmt->fetchAll(PDO::FETCH_ASSOC);
return$result;
}

/**
*執行語句針對INSERT,UPDATE以及DELETE,exec結果返回受影響的行數
*@paramstring$sqlsql指令
*@returninteger
*/
protectedfunction_doExec($sql=''){
$this->_sql=$sql;
returnself::$_dbh->exec($this->_sql);
}

/**
*執行sql語句,自動判斷進行查詢或者執行操作
*@paramstring$sqlSQL指令
*@returnmixed
*/
publicfunctiondoSql($sql=''){
$queryIps='INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOADDATA|SELECT.*INTO|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK';
if(preg_match('/^s*"?('.$queryIps.')s+/i',$sql)){
return$this->_doExec($sql);
}
else{
//查詢操作
return$this->_doQuery($sql);
}
}

/**
*獲取最近一次查詢的sql語句
*@returnString執行的SQL
*/
publicfunctiongetLastSql(){
return$this->_sql;
}

/**
*插入方法
*@paramstring$tbName操作的數據表名
*@paramarray$data欄位-值的一維數組
*@returnint受影響的行數
*/
publicfunctioninsert($tbName,array$data){
$data=$this->_dataFormat($tbName,$data);
if(!$data)return;
$sql="insertinto".$tbName."(".implode(',',array_keys($data)).")values(".implode(',',array_values($data)).")";
return$this->_doExec($sql);
}

/**
*刪除方法
*@paramstring$tbName操作的數據表名
*@returnint受影響的行數
*/
publicfunctiondelete($tbName){
//安全考慮,阻止全表刪除
if(!trim($this->_where))returnfalse;
$sql="deletefrom".$tbName."".$this->_where;
$this->_clear=1;
$this->_clear();
return$this->_doExec($sql);
}

/**
*更新函數
*@paramstring$tbName操作的數據表名
*@paramarray$data參數數組
*@returnint受影響的行數
*/
publicfunctionupdate($tbName,array$data){
//安全考慮,阻止全表更新
if(!trim($this->_where))returnfalse;
$data=$this->_dataFormat($tbName,$data);
if(!$data)return;
$valArr='';
foreach($dataas$k=>$v){
$valArr[]=$k.'='.$v;
}
$valStr=implode(',',$valArr);
$sql="update".trim($tbName)."set".trim($valStr)."".trim($this->_where);
return$this->_doExec($sql);
}

/**
*查詢函數
*@paramstring$tbName操作的數據表名
*@returnarray結果集
*/
publicfunctionselect($tbName=''){
$sql="select".trim($this->_field)."from".$tbName."".trim($this->_where)."".trim($this->_order)."".trim($this->_limit);
$this->_clear=1;
$this->_clear();
return$this->_doQuery(trim($sql));
}

/**
*@parammixed$option組合條件的二維數組,例:$option['field1']=array(1,'=>','or')
*@return$this
*/
publicfunctionwhere($option){
if($this->_clear>0)$this->_clear();
$this->_where='where';
$logic='and';
if(is_string($option)){
$this->_where.=$option;
}
elseif(is_array($option)){
foreach($optionas$k=>$v){
if(is_array($v)){
$relative=isset($v[1])?$v[1]:'=';
$logic=isset($v[2])?$v[2]:'and';
$condition='('.$this->_addChar($k).''.$relative.''.$v[0].')';
}
else{
$logic='and';
$condition='('.$this->_addChar($k).'='.$v.')';
}
$this->_where.=isset($mark)?$logic.$condition:$condition;
$mark=1;
}
}
return$this;
}

/**
*設置排序
*@parammixed$option排序條件數組例:array('sort'=>'desc')
*@return$this
*/
publicfunctionorder($option){
if($this->_clear>0)$this->_clear();
$this->_order='orderby';
if(is_string($option)){
$this->_order.=$option;
}
elseif(is_array($option)){
foreach($optionas$k=>$v){
$order=$this->_addChar($k).''.$v;
$this->_order.=isset($mark)?','.$order:$order;
$mark=1;
}
}
return$this;
}

/**
*設置查詢行數及頁數
*@paramint$pagepageSize不為空時為頁數,否則為行數
*@paramint$pageSize為空則函數設定取出行數,不為空則設定取出行數及頁數
*@return$this
*/
publicfunctionlimit($page,$pageSize=null){
if($this->_clear>0)$this->_clear();
if($pageSize===null){
$this->_limit="limit".$page;
}
else{
$pageval=intval(($page-1)*$pageSize);
$this->_limit="limit".$pageval.",".$pageSize;
}
return$this;
}

/**
*設置查詢欄位
*@parammixed$field欄位數組
*@return$this
*/
publicfunctionfield($field){
if($this->_clear>0)$this->_clear();
if(is_string($field)){
$field=explode(',',$field);
}
$nField=array_map(array($this,'_addChar'),$field);
$this->_field=implode(',',$nField);
return$this;
}

/**
*清理標記函數
*/
protectedfunction_clear(){
$this->_where='';
$this->_order='';
$this->_limit='';
$this->_field='*';
$this->_clear=0;
}

/**
*手動清理標記
*@return$this
*/
publicfunctionclearKey(){
$this->_clear();
return$this;
}

/**
*啟動事務
*@returnvoid
*/
publicfunctionstartTrans(){
//數據rollback支持
if($this->_trans==0)self::$_dbh->beginTransaction();
$this->_trans++;
return;
}

/**
*用於非自動提交狀態下面的查詢提交
*@returnboolen
*/
publicfunctioncommit(){
$result=true;
if($this->_trans>0){
$result=self::$_dbh->commit();
$this->_trans=0;
}
return$result;
}

/**
*事務回滾
*@returnboolen
*/
publicfunctionrollback(){
$result=true;
if($this->_trans>0){
$result=self::$_dbh->rollback();
$this->_trans=0;
}
return$result;
}

/**
*關閉連接
*PHP在腳本結束時會自動關閉連接。
*/
publicfunctionclose(){
if(!is_null(self::$_dbh))self::$_dbh=null;
}

}

2. 使用php+mysql進行開發時,發現有人寫了另外一個類來封裝所有的mysql操作,這樣有必要嗎

有必要的,封裝起來後,直接調用相應的方法就可以,不用寫太多的sql語句,也方便維護,代碼重用性高

3. php封裝一個類能實現mysql資料庫的增刪改查

樓主整理代碼會好一點

4. 求PHP資料庫封裝類操作代碼

<?php
class MySQL{
private $host; //伺服器地址
private $name; //登錄賬號
private $pwd; //登錄密碼
private $dBase; //資料庫名稱
private $conn; //資料庫鏈接資源
private $result; //結果集
private $msg; //返回結果
private $fields; //返回欄位
private $fieldsNum; //返回欄位數
private $rowsNum; //返回結果數
private $rowsRst; //返回單條記錄的欄位數組
private $filesArray = array(); //返回欄位數組
private $rowsArray = array(); //返回結果數組
private $charset='utf8'; //設置操作的字元集
private $query_count=0; //查詢結果次數
static private $_instance; //存儲對象
//初始化類
private function __construct($host='',$name='',$pwd='',$dBase=''){
if($host != '') $this->host = $host;
if($name != '') $this->name = $name;
if($pwd != '') $this->pwd = $pwd;
if($dBase != '') $this->dBase = $dBase;
$this->init_conn();
}
//防止被克隆
private function __clone(){}
public static function getInstance($host='',$name='',$pwd='',$dBase=''){
if(FALSE == (self::$_instance instanceof self)){
self::$_instance = new self($host,$name,$pwd,$dBase);
}
return self::$_instance;
}
public function __set($name,$value){
$this->$name=$value;
}
public function __get($name){
return $this->$name;
}
//鏈接資料庫
function init_conn(){
$this->conn=@mysql_connect($this->host,$this->name,$this->pwd) or die('connect db fail !');
@mysql_select_db($this->dBase,$this->conn) or die('select db fail !');
mysql_query("set names ".$this->charset);
}
//查詢結果
function mysql_query_rst($sql){
if($this->conn == '') $this->init_conn();
$this->result = @mysql_query($sql,$this->conn);
$this->query_count++;
}
//取得欄位數
function getFieldsNum($sql){
$this->mysql_query_rst($sql);
$this->fieldsNum = @mysql_num_fields($this->result);
}
//取得查詢結果數
function getRowsNum($sql){
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
return @mysql_num_rows($this->result);
}else{
return '';
}
}
//取得記錄數組(單條記錄)
function getRowsRst($sql,$type=MYSQL_BOTH){
$this->mysql_query_rst($sql);
if(empty($this->result)) return '';
if(mysql_error() == 0){
$this->rowsRst = mysql_fetch_array($this->result,$type);
return $this->rowsRst;
}else{
return '';
}
}
//取得記錄數組(多條記錄)
function getRowsArray($sql,$type=MYSQL_BOTH){
!empty($this->rowsArray) ? $this->rowsArray=array() : '';
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
while($row = mysql_fetch_array($this->result,$type)) {
$this->rowsArray[] = $row;
}
return $this->rowsArray;
}else{
return '';
}
}
//更新、刪除、添加記錄數
function uidRst($sql){
if($this->conn == ''){
$this->init_conn();
}
@mysql_query($sql);
$this->rowsNum = @mysql_affected_rows();
if(mysql_errno() == 0){
return $this->rowsNum;
}else{
return '';
}
}
//返回最近插入的一條資料庫的id值
function returnRstId($sql){
if($this->conn == ''){
$this->init_conn();
}
@mysql_query($sql);
if(mysql_errno() == 0){
return mysql_insert_id();
}else{
return '';
}
}
//獲取對應的欄位值
function getFields($sql,$fields){
$this->mysql_query_rst($sql);
if(mysql_errno() == 0){
if(mysql_num_rows($this->result) > 0){
$tmpfld = @mysql_fetch_row($this->result);
$this->fields = $tmpfld[$fields];

}
return $this->fields;
}else{
return '';
}
}
//錯誤信息
function msg_error(){
if(mysql_errno() != 0) {
$this->msg = mysql_error();
}
return $this->msg;
}
//釋放結果集
function close_rst(){
mysql_free_result($this->result);
$this->msg = '';
$this->fieldsNum = 0;
$this->rowsNum = 0;
$this->filesArray = '';
$this->rowsArray = '';
}
//關閉資料庫
function close_conn(){
$this->close_rst();
mysql_close($this->conn);
$this->conn = '';
}
//取得資料庫版本
function db_version() {
return mysql_get_server_info();
}
}

5. PHP訪問MYSQL資料庫封裝類(附函數說明)

復制代碼
代碼如下:
<?php
/*
MYSQL
資料庫訪問封裝類
MYSQL
數據訪問方式,php4支持以mysql_開頭的過程訪問方式,php5開始支持以mysqli_開頭的過程和mysqli面向對象
訪問方式,本封裝類以mysql_封裝
數據訪問的一般流程:
1,連接資料庫
mysql_connect
or
mysql_pconnect
2,選擇資料庫
mysql_select_db
3,執行SQL查詢
mysql_query
4,處理返回的數據
mysql_fetch_array
mysql_num_rows
mysql_fetch_assoc
mysql_fetch_row
etc
*/
class
db_mysql
{
var
$querynum
=
0
;
//當前頁面進程查詢資料庫的次數
var
$dblink
;
//資料庫連接資源
//鏈接資料庫
function
connect($dbhost,$dbuser,$dbpw,$dbname='',$dbcharset='utf-8',$pconnect=0
,
$halt=true)
{
$func
=
empty($pconnect)
?
'mysql_connect'
:
'mysql_pconnect'
;
$this->dblink
=
@$func($dbhost,$dbuser,$dbpw)
;
if
($halt
&&
!$this->dblink)
{
$this->halt("無法鏈接資料庫!");
}
//設置查詢字元集
mysql_query("SET
character_set_connection={$dbcharset},character_set_results={$dbcharset},character_set_client=binary",$this->dblink)
;
//選擇資料庫
$dbname
&&
@mysql_select_db($dbname,$this->dblink)
;
}
//選擇資料庫
function
select_db($dbname)
{
return
mysql_select_db($dbname,$this->dblink);
}
//執行SQL查詢
function
query($sql)
{
$this->querynum++
;
return
mysql_query($sql,$this->dblink)
;
}
//返回最近一次與連接句柄關聯的INSERT,UPDATE
或DELETE
查詢所影響的記錄行數
function
affected_rows()
{
return
mysql_affected_rows($this->dblink)
;
}
//取得結果集中行的數目,只對select查詢的結果集有效
function
num_rows($result)
{
return
mysql_num_rows($result)
;
}
//獲得單格的查詢結果
function
result($result,$row=0)
{
return
mysql_result($result,$row)
;
}
//取得上一步
INSERT
操作產生的
ID,只對表有AUTO_INCREMENT
ID的操作有效
function
insert_id()
{
return
($id
=
mysql_insert_id($this->dblink))
>=
0
?
$id
:
$this->result($this->query("SELECT
last_insert_id()"),
0);
}
//從結果集提取當前行,以數字為key表示的關聯數組形式返回
function
fetch_row($result)
{
return
mysql_fetch_row($result)
;
}
//從結果集提取當前行,以欄位名為key表示的關聯數組形式返回
function
fetch_assoc($result)
{
return
mysql_fetch_assoc($result);
}
//從結果集提取當前行,以欄位名和數字為key表示的關聯數組形式返回
function
fetch_array($result)
{
return
mysql_fetch_array($result);
}
//關閉鏈接
function
close()
{
return
mysql_close($this->dblink)
;
}
//輸出簡單的錯誤html提示信息並終止程序
function
halt($msg)
{
$message
=
"<html>\n<head>\n"
;
$message
.=
"<meta
content='text/html;charset=gb2312'>\n"
;
$message
.=
"</head>\n"
;
$message
.=
"<body>\n"
;
$message
.=
"資料庫出錯:".htmlspecialchars($msg)."\n"
;
$message
.=
"</body>\n"
;
$message
.=
"</html>"
;
echo
$message
;
exit
;
}
}
?>

6. php封裝一個class類實現mysql資料庫的增刪該查

<?php
class db{
private $db;
const MYSQL_OPT_READ_TIMEOUT = 11;
const MYSQL_OPT_WRITE_TIMEOUT = 12;
private $tbl_name;
private $where;
private $sort;
private $fields;
private $limit;
public static $_instance = null;
function __construct(){
$cfg = loadConfig('db');
$db = mysqli_init();
$db->options(self::MYSQL_OPT_READ_TIMEOUT, 3);
$db->options(self::MYSQL_OPT_WRITE_TIMEOUT, 1);
@$db->real_connect($cfg['host'],$cfg['user'],$cfg['pwd'],$cfg['db']);
if ($db->connect_error) {
$this->crash($db->errno,$db->error);
}
$db->set_charset("utf8");
$this->db = $db;
//echo $this->db->stat;
}
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self();
}
return self::$_instance;
}
private function __clone() {} //覆蓋__clone()方法,禁止克隆
public function find($conditions = null){
if($conditions) $this->where($conditions);
return $this->getArray($this->buildSql(),1);
}
public function findAll($conditions = null){
if($conditions) $this->where($conditions);
return $this->getArray($this->buildSql());
}
//表
public function t($table){ $this->tbl_name = $table; return $this;}
//條件
public function where($conditions){
$where = '';
if(is_array($conditions)){
$join = array();
foreach( $conditions as $key => $condition ){
$condition = $this->db->real_escape_string($condition);
$join[] = "`{$key}` = '{$condition}'";
}
$where = "WHERE ".join(" AND ",$join);
}else{
if(null != $conditions) $where = "WHERE ".$conditions;
}
$this->where = $where;
return $this;
}
//排序
public function sort($sort){
if(null != $sort) $sort = "ORDER BY {$sort}";
$this->sort = $sort;
return $this;
}
//欄位
public function fields($fields){ $this->fields = $fields; return $this; }
public function limit($limit){$this->limit = $limit; return $this;}
private function buildSql(){
$this->fields = empty($this->fields) ? "*" : $this->fields;
$sql = "SELECT {$this->fields} FROM {$this->tbl_name} {$this->where} {$this->sort}";
accessLog('db_access',$sql);
if(null != $this->limit)$sql .= " limit {$this->limit}";
return $sql;
}
/**
* 返回查詢數據
* @param $sql
* @param bool $hasOne
* @return array|bool|mixed
*/
private function getArray($sql,$hasOne = false){
if($this->db->real_query($sql) ){
if ($result = $this->db->use_result()) {
$row = array();
if($hasOne){
$row = $result->fetch_assoc();
}else{
while($d = $result->fetch_assoc()) $row[] = $d;
}
$result->close();
$this->fields = "*";
return $row;
}else{
return false;
}
}else{
if($this->db->error){
$this->crash($this->db->errno,$this->db->error,$sql);
}
}
}
public function findSql($sql,$hasOne = false){
accessLog('db_access',$sql);
if($this->db->real_query($sql) ){
if ($result = $this->db->use_result()) {
$row = array();
if($hasOne){
$row = $result->fetch_assoc();
}else{
while($d = $result->fetch_assoc()) $row[] = $d;
}
$result->close();
$this->fields = "*";
return $row;
}else{
return false;
}
}else{
if($this->db->error){
$this->crash($this->db->errno,$this->db->error,$sql);
}
}
}
public function create($row){
if(!is_array($row))return FALSE;
$row = $this->prepera_format($row);
if(empty($row))return FALSE;
foreach($row as $key => $value){
$cols[] = '`'.$key.'`';
$vals[] = "'".$this->db->real_escape_string($value)."'";
}
$col = implode(',', $cols);
$val = implode(',', $vals);
$sql = "INSERT INTO `{$this->tbl_name}` ({$col}) VALUES ({$val})";
accessLog('db_access',$sql);
if( FALSE != $this->db->query($sql) ){ // 獲取當前新增的ID
if($this->db->insert_id){
return $this->db->insert_id;
}
if($this->db->affected_rows){
return true;
}
}
return FALSE;
}
//直接執行sql
public function runSql($sql){
accessLog('db_access',$sql);
if( FALSE != $this->db->query($sql) ){ // 獲取當前新增的ID
return true;
}else{
return false;
}
}
public function update($row){
$where = "";
$row = $this->prepera_format($row);
if(empty($row))return FALSE;
foreach($row as $key => $value){
$value = $this->db->real_escape_string($value);
$vals[] = "`{$key}` = '{$value}'";
}
$values = join(", ",$vals);
$sql = "UPDATE {$this->tbl_name} SET {$values} {$this->where}";
accessLog('db_access',$sql);
if( FALSE != $this->db->query($sql) ){ // 獲取當前新增的ID
if( $this->db->affected_rows){
return true;
}
}
return false;
}
function delete(){
$sql = "DELETE FROM {$this->tbl_name} {$this->where}";
if( FALSE != $this->db->query($sql) ){ // 獲取當前新增的ID
if( $this->db->affected_rows){
return true;
}
}
return FALSE;
}
private function prepera_format($rows){
$columns = $this->getArray("DESCRIBE {$this->tbl_name}");
$newcol = array();
foreach( $columns as $col ){
$newcol[$col['Field']] = $col['Field'];
}
return array_intersect_key($rows,$newcol);
}
//崩潰信息
private function crash($number,$message,$sql=''){
$msg = 'Db Error '.$number.':'.$message ;
if(empty($sql)){
echo t('db_crash');
}else{
$msg .= " SQL:".$sql;
echo t('db_query_err');
}
accessLog('db_error',$msg);
exit;
}
}

7. php實現mysql封裝類示例

php封裝mysql類
復制代碼
代碼如下:
<?php
class
Mysql
{
private
$host;
private
$user;
private
$pwd;
private
$dbName;
private
$charset;
private
$conn
=
null;
public
function
__construct()
{
$this->host
=
'localhost';
$this->user
=
'root';
$this->pwd
=
'root';
$this->dbName
=
'test';
$this->connect($this->host,$this->user,$this->pwd);
$this->switchDb($this->dbName);
$this->setChar($this->charset);
}
//負責鏈接
private
function
connect($h,$u,$p)
{
$conn
=
mysql_connect($h,$u,$p);
$this->conn
=
$conn;
}
//負責切換資料庫
public
function
switchDb($db)
{
$sql
=
'use'
.
$db;
$this->query($sql);
}
//負責設置字元集
public
function
setChar($char)
{
$sql
=
'set
names'
.
$char;
$this->query($sql);
}
//負責發送sql查詢
public
function
query($sql)
{
return
mysql_query($sql,$this->conn);
}
//負責獲取多行多列的select結果
public
function
getAll($sql)
{
$list
=
array();
$rs
=
$this->query($sql);
if
(!$rs)
{
return
false;
}
while
($row
=
mysql_fetch_assoc($rs))
{
$list[]
=
$row;
}
return
$list;
}
public
function
getRow($sql)
{
$rs
=
$this->query($sql);
if(!$rs)
{
return
false;
}
return
mysql_fetch_assoc($rs);
}
public
function
getOne($sql)
{
$rs
=
$this->query($sql);
if
(!$rs)
{
return
false;
}
return
mysql_fetch_assoc($rs);
return
$row[0];
}
public
function
close()
{
mysql_close($this->conn);
}
}
echo
'<pre>';
$mysql
=
new
Mysql();
print_r($mysql);
$sql
=
"insert
into
stu
values
(4,'wangwu','99998')";
if($mysql->query($sql)){
echo
"query成功";
}else
{
echo
"失敗";
}
echo
"<br
/>";
$sql
=
"select
*
from
stu";
$arr
=
$mysql->getAll($sql);
print_r($arr);
?>

8. php 封裝MySQL類怎麼,不能執行sql語句query()

看不懂你寫的什麼。給個現成的你

<?php
/**
*CreatedbyPhpStorm.
*User:TAOYU
*Date:14-11-16
*Time:上午1:28
*/
classmysql
{
protected$host;
protected$user;
protected$pwd;
protected$port;
protected$error;
protected$db;
protected$charset;
protected$conn=null;
publicstatic$total;//獲得總條數
publicstatic$pages;//總頁數
publicstatic$pagesize;//每頁顯示條數
public$act_page;//獲取當前頁碼
public$start;//開始條數

//構造方法,初始化時連接資料庫
publicfunction__construct($h='localhost',$u='root',$pwd='123',$port=3306)
{
$this->host=$h;
$this->user=$u;
$this->pwd=$pwd;
$this->port=$port;
$this->connect();
$this->selectDb('bookboss');
$this->setChar('utf8');
}

publicfunction__destruct()
{
mysql_close();
}

//連接方法
publicfunctionconnect()
{
if($this->conn=mysql_connect($this->host,$this->user,$this->pwd,$this->port)){
returntrue;
}else{
$this->error="連接失敗!";
returnfalse;
}
}

//選庫方法
publicfunctionselectDb($dbName)
{
//use後要有空格!!!注意!!!
$sql="use".$dbName;
$this->db=$dbName;
return$this->query($sql);
}

//設置字元集方法
publicfunctionsetChar($char)
{
//setnames後要有空格!!!注意!!!
$sql="setnames".$char;
return$this->query($sql);
}

//查詢方法
publicfunctionquery($sql)
{
$rs=mysql_query($sql,$this->conn);
if(!$rs){
/*$this->error=mysql_error($this->conn);
$this->log($this->error);*/
returnfalse;
}else{
return$rs;
}
}

//取指定數據
/*publicfunctiongetData($page,$pagesize=5)
{
$start=($page-1)*$pagesize;
$rs=$this->query("select*fromstudentlimit$start,$pagesize");
if(!$rs){
returnfalse;
}else{
$list=array();
while($row=mysql_fetch_assoc($rs)){
$list[]=$row;
}
return$list;
}
}*/
//取數據
publicfunctiongetAll($sql)
{
$rs=$this->query($sql);
if(!$rs){
returnfalse;
}else{
$list=array();
while($row=mysql_fetch_assoc($rs)){
$list[]=$row;
}
return$list;
}
}
//返回sql語句結果條數
publicfunctiongetNums($sql){
returnmysql_num_rows($this->query($sql));
}
//insert插入數據方法
publicfunctioninsert($sql)
{

}

//讀取錯誤方法
publicfunctiongetError()
{
return$this->error;
}
//記錄日誌方法
/*publicfunctionlog($err){
$time=date('Y-m-dH:i:s',time());
if(file_exists("./log.txt")){
$contents=file_get_contents("./log.txt");
$contents.="$time ".$err." ";
file_put_contents('./log.txt',$contents);
}else{
$filename='./log.txt';
$str='';
writefile($filename,$str);
$contents=file_get_contents("./log.txt");
$contents.="$time ".$err." ";
file_put_contents('./log.txt',$contents);
}

}*/
}
熱點內容
十一代思域哪個配置劃算 發布:2024-05-07 07:59:12 瀏覽:350
鴻蒙系統和安卓系統哪個大 發布:2024-05-07 07:46:37 瀏覽:622
安卓平台用什麼虛擬機 發布:2024-05-07 07:44:14 瀏覽:246
ta柵格演算法 發布:2024-05-07 07:03:23 瀏覽:802
符號源碼 發布:2024-05-07 06:26:09 瀏覽:707
玩hypixel伺服器ip地址要什麼版本 發布:2024-05-07 06:22:50 瀏覽:62
代碼為什麼要編譯 發布:2024-05-07 06:22:48 瀏覽:495
java面試復習 發布:2024-05-07 06:01:15 瀏覽:658
suftp 發布:2024-05-07 06:00:40 瀏覽:880
編程的tr 發布:2024-05-07 05:37:25 瀏覽:423