<?php
// 封装mysql类
/*
1:连接数据库
2:发送sql查询
3:如果是select语句,返回数组
*/
class mysql {
protected $host;
protected $user;
protected $passwd;
protected $port;
protected $db;
protected $charset = 'utf8';
protected $error;
protected $conn = null; // 准备用来存储连接的资源
public function __construct($h='localhost',$u='root',$pwd='root',$port=3306) {
$this->host = $h;
$this->user = $u;
$this->passwd = $pwd;
$this->port = $port;
$this->connect();
}
public function connect() {
if($this->conn = mysql_connect($this->host,$this->user,$this->passwd,$this->port)) {
return true;
} else {
$this->error = '连接失败';
return false;
}
}
public function query($sql) {
$rs = mysql_query($sql,$this->conn);
if(!$rs) {
$this->error = mysql_error($this->conn);
$this->log($this->error);
return false;
}
return $rs;
}
//mysql_fetch_assoc() 返回关联数组,以表中的列名作为数组键名
public function assocSql($sql){
$rs = $this->query($sql);
if(!$rs) {
return false;
}
// 如果真,应该while取数据
$list = array();
while($row = mysql_fetch_assoc($rs)) {
$list[] = $row;
}
return $list;
}
//mysql_fetch_array() 返回assoc+row的并集,既有数字键名,又有列名作键名
public function arraySql($sql){
$rs=mysql_query($sql);
if(!$rs){
echo '数据为空';
return false;
}
$arr=array();
while($row=mysql_fetch_array($rs)){
$arr[]=$row;
}
return $arr;
}
// mysql_fetch_row, 是返回索引数组,键名从0开始,逐一递增
public function rowSql($sql){
$rs=mysql_query($sql);
if(!$rs){
echo '数据为空';
return false;
}
$arr=array();
while($row=mysql_fetch_row($rs)){
$arr[]=$row;
}
return $arr;
}
// 封装一个getRow方法,返回一行记录
// 参数:$sql
// 返回: array,false
public function getRow($sql) {
$rs = $this->query($sql);
if(!$rs) {
return false;
}
return mysql_fetch_assoc($rs);
}
// 封装一个getOne方法,
// 参数: $sql
// 返回: int,str(单一的值)
public function getOne($sql) {
$rs = $this->query($sql);
if(!$rs) {
return false;
}
$tmp = mysql_fetch_row($rs);
return $tmp[0];
}
// 加一个选库的方法
public function usedb($dbname) {
$sql = 'use '.$dbname;
$this->db = $dbname;
return $this->query($sql);
}
// 加一个声明字符集的方法
public function setchar($char) {
$sql = 'set names ' . $char;
return $this->query($sql);
}
// 开放一个读取错误的方法
public function getError() {
return $this->error;
}
// 日志记录功能
protected function log($err) {
$cont = file_get_contents('./log.txt');
$cont .= $err . "\r\n";
file_put_contents('./log.txt',$cont);
}
}
header('content-type:text/html;charset=utf-8');
$db = new mysql();
//print_r($db);
$db->connect();
$db->usedb('eshop');
$db->setchar('utf8');
//$sql = 'select * from sw_user limit 1';
$sql = 'select * from sw_user';
if($list = $db->assocSql($sql)) {
echo '<pre>';
print_r($list);
echo '</pre>';
} else {
echo '错误,信息如下';
echo $db->getError();
}