当前位置:首页 » 编程语言 » 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);
}

}*/
}
热点内容
寒灵之剑脚本 发布:2025-02-07 06:57:12 浏览:118
解压的窗口 发布:2025-02-07 06:44:34 浏览:797
android身份证 发布:2025-02-07 06:36:43 浏览:430
python的库在哪 发布:2025-02-07 06:30:24 浏览:348
带锁的铅笔如何改密码 发布:2025-02-07 06:18:05 浏览:164
ubuntu搭建samba服务器 发布:2025-02-07 05:52:54 浏览:54
小型企业网如何配置可以互通 发布:2025-02-07 05:33:56 浏览:243
09年crv哪个配置好 发布:2025-02-07 05:17:31 浏览:555
nvm源码编译 发布:2025-02-07 05:13:19 浏览:126
防伪码查询源码 发布:2025-02-07 05:09:39 浏览:770