MySQL数据库连接类mysql.class.php
说明:
MySQL数据库连接类,常用操作:
connect //连接数据库服务器(mysql_connect) 、
query //执行查询(mysql_query)、
rows //取得结果集的总数(mysql_num_rows)、
insertId //取得上一步INSERT操作产生的ID(mysql_insert_id)、
fetchArray //从结果集中作为数组取得一行(mysql_fetch_array)、
getOne //获取一条记录、
affectedRows //前一次操作所影响的记录行数(mysql_affected_rows)、
begin、rollback、commit //事务启动、回滚、提交
error、errno //错误信息。
用法:
取一条数据:
<?php
include('mysql.class.php');
$db = new mysql('localhost:3307','upall','pwd','testDb');
$rs = $db->getOne("SELECT `id` FROM `member` WHERE `user` = 'upall' LIMIT 1");
if (!empty($rs['id'])){
echo '登录成功';
}else{
echo '用户名或密码错误';
}
?>
输出列表:
<?php
include('mysql.class.php');
$db = new mysql('localhost:3307','upall','pwd','testDb');
$sql = "SELECT * FROM `member`";
$query = $db->query($sql);
$rows = $db->rows($query);
while ($rs = $db->fetchArray($query)){
echo $rs['user'] . '<br />';
}
echo "共 $rows 条记录";
?>
事务处理:
MySQL中只有InnoDB和BDB类型的数据表才能支持事务处理!其他的类型是不支持的。
<?php
include('mysql.class.php');
$db = new mysql('localhost:3307','upall','pwd','testDb');
$db->begin(); // 启动事务
$sqlReduction = "UPDATE `account` SET `money` = `money` - 10000 WHERE `id` = 1 LIMIT 1 FOR UPDATE";
$queryReduction = $db->query($sqlReduction);
if ($db->error()){
$db->rollback(); // 回滚事务
echo '扣钱时出错啦~';
}else{
$sqlIncrease = "UPDATE `account` SET `money` = `money` + 10000 WHERE `id` = 2 LIMIT 1";
$queryIncrease = $db->query($sqlReduction);
if ($db->error()){
$db->rollback(); // 回滚事务
echo '加钱时出错啦~';
}else{
$db->commit();// 提交事务
echo '转款成功啦。';
}
}
?>
自动保存:
<form action="?add">
<!-- 属性“name”与表字段对应 -->
<label>标题:<input type="text" name="title" /></label>
<label>作者:<input type="text" name="author" /></label>
<label>内容:<input type="text" name="content" /></label>
<button type="submit">添加</button>
</form>
<?php
if (isset($_GET['add'])){
include('mysql.class.php');
$db = new mysql('localhost:3307','upall','pwd','testDb');
$rs = $db->insert('news_info'); //news_info是表名,自动处理POST
if (TRUE == $rs){ //错会直接抛出异常
echo '录入成功';
}
}
?>
自动更新:
<?php
// 这里可以参考上文中的getOne()
$rs = ....
?>
<form action="?save">
<!-- 属性“name”与表字段对应 -->
<label>标题:<input type="text" name="title" value="<?php echo $rs['title'];?>" /></label>
<label>作者:<input type="text" name="author" value="<?php echo $rs['author'];?>" /></label>
<label>内容:<input type="text" name="content" value="<?php echo $rs['content'];?>" /></label>
<input type="hidden" name="id" value="<?php echo $rs['id'];?>" />
<button type="submit">添加</button>
</form>
<?php
if (isset($_GET['save'])){
include('mysql.class.php');
$db = new mysql('localhost:3307','upall','pwd','testDb');
$id = (int)$_POST['id'];
$rs = $db->update($id,'news_info'); // 更新id为$id的记录,news_info是表名,自动处理POST
if (TRUE == $rs){ //错会直接抛出异常
echo '更新成功';
}
}
?>
下载:
mysql.class.php.tar.gz (为什么此附件的地址不能分享给朋友们下载?)
代码:
<?php
/**
* 说明:MySQL数据库连接类
* 时间:13:04 2011年7月28日 星期四
* $host = 服务器地址(“$host”或“$host:PORT”)
* $name = 用户名
* $pwd = 密码
* $db = 数据库
* ----------------------------------
* 用法:
* $dbHost = 'localhost:3307'
* $dbUser = 'root'
* $dbPwd = 'upall'
* $dbName = 'mysql'
* $db = new mysql($dbHost, $dbUser, $dbPwd, $dbName); // 实例后直接连接数据库
* $sql = "SELECT * FROM user WHERE User LIKE '%upall%'";
* $query = $db->query($sql); // 执行查询
* while ($rs = $db->fetchArray($query)){
* echo $rs['User'] . '<br />';
* }
*/
class mysql{
public $host = 'localhost:3306';
public $user = 'upall';
public $pwd = '';
public $db = 'mysql';
public $charset = 'utf8'; // 注意:mysql中不是utf-8,没有减号
public $linkId;
public $sql = '';
function __construct($host = '', $user = '', $pwd = '', $db = '', $charset = ''){
empty($host) ? '' : $this->host = $host;
empty($user) ? '' : $this->user = $user;
empty($pwd) ? '' : $this->pwd = $pwd;
empty($db) ? '' : $this->db = $db;
empty($charset) ? '' : $this->charset = $charset;
$this->connect();
}
// 打开一个到 MySQL 服务器的连接
function connect(){
$this->linkId = @mysql_connect($this->host,$this->user,$this->pwd);
if ($this->linkId) {
$this->selectDb($this->db);
mysql_query("SET NAMES $this->charset");
}else{
$this->error('无法连接数据库服务器',__LINE__);
return FALSE;
}
}
function selectDb($dbName){
if (!empty($this->error)) return FALSE;
$rs = @mysql_select_db($this->db, $this->linkId);
if (!$rs){
$this->error('选定数据库失败',__LINE__);
return FALSE;
}
}
// 发送一条 MySQL 查询
function query($sql){
$this->sql = $sql;
$result = @mysql_query($sql, $this->linkId);
$mysqlError = mysql_error();
if (!empty($mysqlError)){
$mysqlError .= '<br />(SQL: ' . $sql . ')';
$this->error($mysqlError,__LINE__);
}
return $result;
}
// 取得结果集的总数
function rows($query){
$rows = @mysql_num_rows($query);
$mysqlError = mysql_error();
if (!empty($mysqlError)) $this->error($mysqlError,__LINE__);
return $rows;
}
// 取得上一步 INSERT 操作产生的 ID
function insertId(){
$insertId = @mysql_insert_id($this->linkId);
$mysqlError = mysql_error();
if (!empty($mysqlError)) $this->error($mysqlError,__LINE__);
return $insertId;
}
// 从结果集中取得一行
function fetchArray($query){
$result = @mysql_fetch_array($query);
$mysqlError = mysql_error();
if (!empty($mysqlError)) $this->error($mysqlError,__LINE__);
return $result;
}
// 获取一条记录
function getOne($sql){
return $this->fetchArray($this->query($sql));
}
// 前一次操作所影响的记录行数
function affectedRows(){
$aRows = @mysql_affected_rows();
$mysqlError = mysql_error();
if (!empty($mysqlError)) $this->error($mysqlError,__LINE__);
return $aRows;
}
// 自动事务开关
function autocommit($bool){
if (TRUE === $bool){
mysql_query("SET AUTOCOMMIT=1");
}elseif(FALSE === $bool){
mysql_query("SET AUTOCOMMIT=0");
}
}
// 错误信息
function error($msg = '',$line = 0){
if (empty($msg)) return FALSE;
try{
throw new Exception($msg);
}
catch(Exception $e){
//echo '<br />Message: ' .$e->getMessage();
#$file = $e->getFile();
#$file = pathinfo($file);
#$file = $file['basename'];
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><div style="margin:10% auto 0;border:dotted 1px #F90;background-color:#F5DE38;width:400px;padding:20px;color:#C00;"><strong>错误: </strong>数据库读取出错 <strong>Line: </strong>' . $line . '<br /><strong>详细: </strong>' .$msg. '<div style="text-align:right;">管理员: <a href="http://upall.cn/" target="_blank" title="user@upall.cn">upall™</a></div></div>';
exit;
}
}
// 错误号
function errno(){
return mysql_errno();
}
// 开始事务
function begin(){
$this->query('START TRANSACTION');
}
// 回滚事务
function rollback(){
$this->query('ROLLBACK');
}
// 提交事务
function commit(){
$this->query('COMMIT');
}
// 自动添加
function insert($tableName){
global $_POST;
// 处理接收到的数据
if (isset($_POST)){
foreach ($_POST as $k => $v){
${$k} = escapeData($v);
}
}else{
$this->error('错误(不允许添加空数据)',__LINE__);
return FALSE;
}
// 生成包含数据的SQL
$dataDb = $this->db;
$this->db = 'information_schema';
$this->selectDb($this->db);
$sql = "SELECT
COLUMN_NAME AS col
FROM `COLUMNS`
where table_name = '$tableName'
AND COLUMN_NAME <> 'id'";
$query = $this->query($sql);
$rows = $this->rows($query);
if (0 == $rows) {
$this->error('不能添加数据(数据表中没有字段)');
return FALSE;
}
$colArrayCol[0] = '`id`';
$colArrayValue[0] = 'NULL';
$index = 1;
while($result = $this->fetchArray($query)){
$tempVarName = ${$result['col']};
if (!empty($tempVarName)){// 不更新无值的字段
$colArrayCol[$index] = '`' . $result['col'] . '`'; // 表字段集
$colArrayValue[$index] = '\'' . ${$result['col']} . '\''; // 表字段对应的数据集
}
$index++;
}
$sql = '';
$sql .= "INSERT INTO `$tableName` (";
$sql .= implode(', ',$colArrayCol);
$sql .= ') VALUES (';
$sql .= implode(', ',$colArrayValue);
$sql .= ')';
// 执行插入
$this->db = $dataDb;
$this->selectDb($this->db);
$rs = $this->query($sql);
return TRUE;
}
// 自动更新
function update($id, $tableName){
global $_POST;
// 判断记录是否存在
$existSql = "SELECT id FROM `$tableName` WHERE id = '$id' LIMIT 1";
$rows = $this->rows($this->query($existSql));
if (0 == $rows) $this->error('错误(您要更新的记录不存在)',__LINE__);
// 读取表结构
$dataDb = $this->db;
$this->db = 'information_schema';
$this->selectDb($this->db);
$sql = "SELECT
COLUMN_NAME AS col
FROM `COLUMNS`
where table_name = '$tableName'
AND COLUMN_NAME <> 'id'";
$query = $this->query($sql);
$rows = $this->rows($query);
if (0 == $rows) {
$this->error('不能添加数据(数据表中没有字段)',__LINE__);
return FALSE;
}
// 生成SQL
$colSqlArray = array();
while ($colRs = $this->fetchArray($query)){
foreach ($_POST as $k => $v){
if ($k == $colRs['col']){ // 如果有需要更新的字段……
$col = $colRs['col'];
$v = escapeData($v);
$colSqlArray[] = "`$col` = '$v'"; // ……则生成相应的SQL
break;
}
}
}
if (empty($colSqlArray)){
$this->error('没有获取到需要更新的数据',__LINE__); // POST传进了0个需要更新的字段
}
$sql = '';
$sql .= "UPDATE `$tableName` SET ";
$sql .= implode(', ',$colSqlArray);
$sql .= " WHERE `id` = '$id' LIMIT 1 ;";
// 执行更新
$this->db = $dataDb;
$this->selectDb($this->db);
$rs = $this->query($sql);
return TRUE;
}
}
?>
<完>