1. <!--?php
  2.  
  3. /**
  4. +----------------------------------
  5. * MySQL操作类库
  6. +----------------------------------
  7. * @author 马犇 <www.imaben.com-->
  8. +----------------------------------
  9. * @version 1.2 (2013-5-31)
  10. +----------------------------------
  11. */
  12.  
  13. include (dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.php');
  14.  
  15. define('CLIENT_MULTI_RESULTS', 131072);
  16.  
  17. class mysql {
  18.  
  19. /* 主机地址 */
  20.  
  21. private $Host = '127.0.0.1';
  22.  
  23. /* 数据库名称 */
  24. private $dbName = DB_NAME;
  25.  
  26. /* 用户名 */
  27. private $UserName = DB_USER;
  28.  
  29. /* 连接密码 */
  30. private $Password = DB_PWD;
  31.  
  32. /* 数据库编码 */
  33. private $dbCharSet = 'utf8';
  34.  
  35. /* 错误信息 */
  36. private $errorMsg;
  37.  
  38. /* 最后一次执行的SQL */
  39. private $lastSql;
  40.  
  41. /* 字段信息 */
  42. private $fields = array();
  43.  
  44. /* 最后一次插入的ID */
  45. public $lastInsID = null;
  46.  
  47. /* 数据库连接ID */
  48. private $linkID = 0;
  49.  
  50. /* 当前查询ID */
  51. private $queryID = null;
  52.  
  53. /*主键*/
  54. private $pk = null;
  55.  
  56. public function __construct($DBName = '') {
  57. if ($DBName != '')
  58. $this->dbName = $DBName;
  59. $this->connect();
  60. }
  61.  
  62. /**
  63. +----------------------------------------------------------
  64. * 连接数据库方法
  65. +----------------------------------------------------------
  66. * @access public
  67. +----------------------------------------------------------
  68. */
  69. public function connect() {
  70.  
  71. if ($this->linkID == 0) {
  72. $this->linkID = mysql_connect($this->Host, $this->UserName, $this->Password, true, CLIENT_MULTI_RESULTS);
  73. if (!$this->linkID) {
  74. $this->errorMsg = '数据库连接错误\r\n' . mysql_error();
  75. $this->halt();
  76. }
  77. }
  78. if (!mysql_select_db($this->dbName, $this->linkID)) {
  79. $this->errorMsg = '打开数据库失败' . mysql_error($this->linkID);
  80. $this->halt('打开数据库失败');
  81. }
  82. $dbVersion = mysql_get_server_info($this->linkID);
  83. if ($dbVersion >= "4.1") {
  84. //使用UTF8存取数据库 需要mysql 4.1.0以上支持
  85. mysql_query("SET NAMES '" . $this->dbCharSet . "'", $this->linkID);
  86. }
  87. //设置CharSet
  88. mysql_query('set character set \'' . $this->dbCharSet . '\'', $this->linkID);
  89. //设置 sql_model
  90. if ($dbVersion > '5.0.1') {
  91. mysql_query("SET sql_mode=''", $this->linkID);
  92. }
  93. }
  94.  
  95. /**
  96. +----------------------------------------------------------
  97. * 释放查询结果
  98. +----------------------------------------------------------
  99. * @access public
  100. +----------------------------------------------------------
  101. */
  102. public function free() {
  103. if($this->queryID != null)
  104. mysql_free_result($this->queryID);
  105. $this->queryID = null;
  106. }
  107.  
  108. /**
  109. +----------------------------------------------------------
  110. * 执行语句
  111. +----------------------------------------------------------
  112. * @access public
  113. +----------------------------------------------------------
  114. * @param string $sql sql指令
  115. +----------------------------------------------------------
  116. * @return bool or resource
  117. +----------------------------------------------------------
  118. */
  119. public function execute($sql) {
  120.  
  121. if ($this->linkID == 0)
  122. $this->connect();
  123. $this->lastSql = $sql;
  124. $this->queryID = mysql_query($sql);
  125. if (false == $this->queryID) {
  126. $this->errorMsg = 'SQL语句执行失败\r\n' . mysql_error($this->linkID);
  127. return false;
  128. } else {
  129. return $this->queryID;
  130. }
  131. }
  132.  
  133. /**
  134. +----------------------------------------------------------
  135. * 获取记录集的行数
  136. +----------------------------------------------------------
  137. * @access public
  138. +----------------------------------------------------------
  139. * @param string $sql sql指令 可为空
  140. * 如为空:返回上一结果集记录数
  141. * 如不为空:返回当前sql语句的记录数
  142. +----------------------------------------------------------
  143. * @return integer
  144. +----------------------------------------------------------
  145. */
  146. public function getRowsNum($sql = '') {
  147.  
  148. if ($this->linkID == 0) {
  149. $this->connect();
  150. }
  151. if ($sql != '') {
  152. $this->execute($sql);
  153. }
  154. return mysql_num_rows($this->queryID);
  155. }
  156.  
  157. /**
  158. +----------------------------------------------------------
  159. * 表单数据直接插入到数据表中
  160. +----------------------------------------------------------
  161. * @access public
  162. +----------------------------------------------------------
  163. * @param string $tableName 数据表名
  164. +----------------------------------------------------------
  165. * @return 执行成功返回插入记录的索引记录,失败返回false
  166. +----------------------------------------------------------
  167. */
  168. public function form2db($tableName) {
  169.  
  170. $_POST["add_time"] = date('Y-m-d H:i:s');
  171. $data = $_POST;
  172. $this->fields = $this->getFields($tableName);
  173. $data = $this->_facade($data);
  174. if ($this->insert($tableName, $data)) {
  175. return $this->lastInsID;
  176. } else {
  177. return false;
  178. }
  179. }
  180.  
  181. /**
  182. +----------------------------------------------------------
  183. * 数据直接插入到数据表中
  184. +----------------------------------------------------------
  185. * @access public
  186. +----------------------------------------------------------
  187. * @param string $tableName 数据表名
  188. +----------------------------------------------------------
  189. * @param array $data 插入的数据 数据键名对应字段名,键值对应值
  190. +----------------------------------------------------------
  191. * @return boolean
  192. +----------------------------------------------------------
  193. */
  194. public function insert($tableName, $data) {
  195.  
  196. $values = $fields = array();
  197. foreach ($data as $key => $val) {
  198. $value = '\'' . addslashes($val) . '\'';
  199. if (is_scalar($value)) { // 过滤非标量数据
  200. $values[] = $value;
  201. $fields[] = $key;
  202. }
  203. }
  204. $sql = 'INSERT INTO ' . trim($tableName) . '(' . implode(',', $fields) . ') VALUES(' . implode(',', $values) . ')';
  205. if ($this->execute($sql)) {
  206. $this->errorMsg = '插入失败\r\n' . mysql_error($this->linkID);
  207. $this->lastInsID = mysql_insert_id($this->linkID);
  208. return true;
  209. } else {
  210. return false;
  211. }
  212. }
  213.  
  214. /**
  215. +----------------------------------------------------------
  216. * 更新操作
  217. +----------------------------------------------------------
  218. * @access public
  219. +----------------------------------------------------------
  220. * @param string $tableName 数据表名
  221. +----------------------------------------------------------
  222. * @param array $data 插入的数据 数据键名对应字段名,键值对应值
  223. +----------------------------------------------------------
  224. * @param array $condition 更新条件,为安全起见,不能为空
  225. +----------------------------------------------------------
  226. * @param array $isForm 可为空,缺省为true
  227. * 如果为true,会当成表单更新数据表来处理,自动映射字段
  228. * 如果为false,会当成普通的更新来处理,不会自动映射字段
  229. +----------------------------------------------------------
  230. * @return boolean
  231. +----------------------------------------------------------
  232. */
  233. public function update($tableName, $data, $condition, $isForm = true) {
  234.  
  235. if (empty($condition)) {
  236. $this->errorMsg = '没有设置更新条件';
  237. return false;
  238. }
  239. //处理分解condition
  240. if(is_array($condition)){
  241. $condition = self::_parseCondition($condition);
  242. }
  243. if ($isForm) {
  244. $this->fields = $this->getFields($tableName);
  245. $data = $this->_facade($data);
  246. }
  247. $sql = 'UPDATE ' . trim($tableName) . ' SET ';
  248. foreach ($data as $key => $val) {
  249. $sql .= $key . '=\'' . $val . '\',';
  250. }
  251. $sql = substr($sql, 0, strlen($sql) - 1);
  252. $sql .= ' WHERE ' . $condition;
  253. if ($this->execute($sql)) {
  254. return true;
  255. } else {
  256. $this->errorMsg = '更新失败\r\n' . mysql_error($this->linkID);
  257. return false;
  258. }
  259. }
  260.  
  261. /**
  262. +----------------------------------------------------------
  263. * 删除操作
  264. +----------------------------------------------------------
  265. * @access public
  266. +----------------------------------------------------------
  267. * @param string $tableName 数据表名
  268. +----------------------------------------------------------
  269. * @param array $condition 更新条件,为安全起见,不能为空
  270. +----------------------------------------------------------
  271. * @return boolean
  272. +----------------------------------------------------------
  273. */
  274. public function delete($tableName, $condition) {
  275. //处理分解condition
  276. if(is_array($condition)){
  277. $condition = self::_parseCondition($condition);
  278. }
  279. $sql = 'delete from ' . $tableName . ' where 1=1 and ' . $condition;
  280. if (!$this->execute($sql))
  281. return false;
  282. return true;
  283. }
  284.  
  285. /**
  286. +----------------------------------------------------------
  287. * 利用__call魔术方法实现一些特殊的Model方法
  288. +----------------------------------------------------------
  289. * @access public
  290. +----------------------------------------------------------
  291. * @param string $method 方法名称
  292. * @param array $args 调用参数
  293. +----------------------------------------------------------
  294. * @return mixed
  295. +----------------------------------------------------------
  296. */
  297. public function __call($method,$args){
  298.  
  299. /*根据某个字段获取记录字段的值
  300. * 例1:getFieldByid(student_info,100,name)---获取学生表中id为100的学生姓名
  301. * 例2:getFieldByxh(student_info,201215030223,address)---获取学生表中学号为201015030223的地址
  302. * 注:"getFieldBy"不区分大小写,后面的字段名区分大小写
  303. * 返回值:string
  304. */
  305. if(strtolower(substr($method,0,10)) == 'getfieldby'){
  306. $name = substr($method,10);
  307. $sql = 'select `'.$args[2].'` from '.$args[0].' where '.$name.'=\''.$args[1].'\'';
  308. if($this->execute($sql)){
  309. $row = mysql_fetch_array($this->queryID);
  310. return $row[0];
  311. }else{
  312. return false;
  313. }
  314. }
  315. /*根据某个字段和值获取某条记录
  316. * 例1:getByid(student_info,100)---获取学生表中id为100的学生信息
  317. * 例2:getByxh(student_info,201215030223)---获取学生表中学号为201015030223的学生信息
  318. * 注:"getBy"不区分大小写,后面的字段名区分大小写
  319. * 返回值:array
  320. */
  321. elseif(strtolower(substr($method,0,5)) == 'getby'){
  322. $ret = array();
  323. $name = substr($method,5);
  324. $sql = 'select * from '.$args[0].' where '.$name.'=\''.$args[1].'\'';
  325. if($this->execute($sql)){
  326. $row = mysql_fetch_array($this->queryID);
  327. return $row;
  328. }else{
  329. return false;
  330. }
  331. }
  332. }
  333.  
  334. /**
  335. +----------------------------------------------------------
  336. * 弹出错误提示,并终止运行
  337. +----------------------------------------------------------
  338. * @access public
  339. +----------------------------------------------------------
  340. * @param string $msg 错误消息,可为空
  341. +----------------------------------------------------------
  342. */
  343. public static function halt($msg = '') {
  344. if ($msg != '') {
  345. $msg .= '\r\n';
  346. }
  347. $error = mysql_error();
  348. die($msg);
  349. }
  350.  
  351. /**
  352. +----------------------------------------------------------
  353. * 获取最后一次查询ID
  354. +----------------------------------------------------------
  355. * @access public
  356. +----------------------------------------------------------
  357. */
  358. public function getQueryId(){
  359. return $this->queryID;
  360. }
  361.  
  362. /**
  363. +----------------------------------------------------------
  364. * 获取最后一次数据库操作错误信息
  365. +----------------------------------------------------------
  366. * @access public
  367. +----------------------------------------------------------
  368. */
  369. public function getLastError() {
  370.  
  371. return $this->errorMsg;
  372. }
  373.  
  374. /**
  375. +----------------------------------------------------------
  376. * 获取最后一次执行的SQL语句
  377. +----------------------------------------------------------
  378. * @access public
  379. +----------------------------------------------------------
  380. */
  381. public function getLastSql() {
  382.  
  383. return $this->lastSql;
  384. }
  385.  
  386. /**
  387. +----------------------------------------------------------
  388. * 获取最后一次插入数据库记录的索引ID号
  389. +----------------------------------------------------------
  390. * @access public
  391. +----------------------------------------------------------
  392. */
  393. public function getLastInsID() {
  394. return $this->lastInsID;
  395. }
  396.  
  397. /**
  398. +----------------------------------------------------------
  399. * 获取上一次操作影响的行数
  400. +----------------------------------------------------------
  401. * @access public
  402. +----------------------------------------------------------
  403. */
  404. public function getAffectedRows() {
  405. return mysql_affected_rows($this->linkID);
  406. }
  407.  
  408. /**
  409. +----------------------------------------------------------
  410. * 取得数据表的字段信息
  411. +----------------------------------------------------------
  412. * @access public
  413. +----------------------------------------------------------
  414. */
  415. public function getFields($tableName) {
  416. $result = array();
  417. $this->execute('SHOW COLUMNS FROM ' . $this->parseKey($tableName));
  418. while ($row = mysql_fetch_array($this->queryID)) {
  419. $result[] = $row;
  420. }
  421. $info = array();
  422. if ($result) {
  423. foreach ($result as $key => $val) {
  424. $info[$val['Field']] = array(
  425. 'name' => $val['Field'],
  426. 'type' => $val['Type'],
  427. 'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
  428. 'default' => $val['Default'],
  429. 'primary' => (strtolower($val['Key']) == 'pri'),
  430. 'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
  431. );
  432. }
  433. }
  434. return $info;
  435. }
  436.  
  437. /**
  438. +----------------------------------------------------------
  439. * 字段和表名处理添加`
  440. +----------------------------------------------------------
  441. * @access protected
  442. +----------------------------------------------------------
  443. * @param string $key
  444. +----------------------------------------------------------
  445. * @return string
  446. +----------------------------------------------------------
  447. */
  448. protected function parseKey(&$key) {
  449. $key = trim($key);
  450. if (false !== strpos($key, ' ') || false !== strpos($key, ',') || false !== strpos($key, '*') || false !== strpos($key, '(') || false !== strpos($key, '.') || false !== strpos($key, '`')) {
  451. //如果包含* 或者 使用了sql方法 则不作处理
  452. } else {
  453. $key = '`' . $key . '`';
  454. }
  455. return $key;
  456. }
  457.  
  458. /**
  459. +----------------------------------------------------------
  460. * 对保存到数据库的数据进行处理
  461. +----------------------------------------------------------
  462. * @access protected
  463. +----------------------------------------------------------
  464. * @param mixed $data 要操作的数据
  465. +----------------------------------------------------------
  466. * @return boolean
  467. +----------------------------------------------------------
  468. */
  469. private function _facade($data) {
  470. // 检查非数据字段
  471. if (!empty($this->fields)) {
  472. foreach ($data as $key => $val) {
  473. if (!array_key_exists($key, $this->fields)) {
  474. unset($data[$key]);
  475. }
  476. }
  477. }
  478. return $data;
  479. }
  480.  
  481. public function close(){
  482. mysql_close($this->linkID);
  483. }
  484.  
  485. public function __destruct(){
  486. $this->close();
  487.  
  488. }
  489.  
  490. /*
  491. ** 2013.5.25新增
  492. */
  493.  
  494. public function getPk($table){
  495. //将pk置为空
  496. $this->pk = null;
  497. $result = $this->getFields($table);
  498. foreach($result as $key => $val){
  499. if($val['primary']){
  500. $this->pk = $key;
  501. break;
  502. }
  503. }
  504. return $this->pk;
  505. }
  506.  
  507. public function fetch(&$rst = null , $array_type = MYSQL_ASSOC){
  508. if($rst == null){
  509. $rst = $this->queryID;
  510. }
  511. if($this->queryID)
  512. return mysql_fetch_array($rst , $array_type);
  513. else
  514. return false;
  515. }
  516.  
  517. //分解条件
  518. private function _parseCondition($condition , $operator='AND'){
  519. $return = '';
  520. if (is_array($condition)) {
  521. $index = 0;
  522. foreach ($condition as $key => $value) {
  523. if ($index) {
  524. $return .= " ".$operator;
  525. }
  526. $return .= "`{$key}`='{$value}'";
  527. $index++;
  528. }
  529. return $return;
  530. }else{
  531. return false;
  532. }
  533. }
  534.  
  535. /*事务处理开始*/
  536. public function beginTransaction(){
  537. $this->execute("START TRANSACTION");
  538. }
  539.  
  540. public function commit(){
  541. $this->execute("COMMIT");
  542. }
  543.  
  544. public function rollback(){
  545. $this->execute("ROLLBACK");
  546. }
  547. /*事务处理结束*/
  548.  
  549. //根据条件查找一条记录
  550. public function find($table,$condition = null,$field = null){
  551. if(is_array($condition)){
  552. $condition = self::_parseCondition($condition);
  553. }
  554. //处理condition和field
  555. $condition = $condition == null ? null : (is_array($condition) ? self::_parseCondition($condition) : $condition);
  556. $field = $field == null ? '*' : (is_array($field) ? implode(",",$field) : $field);
  557. $sql = 'SELECT ' . $field . ' FROM '.$table;
  558. if($condition != null){
  559. $sql .= " WHERE " . $condition;
  560. }
  561. return $this->findOneBySql($sql);
  562. }
  563.  
  564. //查找所有记录
  565. public function findAll($table,$condition = null,$field = null){
  566. if(is_array($condition)){
  567. $condition = self::_parseCondition($condition);
  568. }
  569. //处理condition和field
  570. $condition = $condition == null ? null : (is_array($condition) ? self::_parseCondition($condition) : $condition);
  571. $field = $field == null ? '*' : (is_array($field) ? implode(",",$field) : $field);
  572. $sql = 'SELECT ' . $field . ' FROM '.$table;
  573. if($condition != null){
  574. $sql .= " WHERE " . $condition;
  575. }
  576. return $this->findallBySql($sql);
  577. }
  578.  
  579. public function findOneBySql($sql){
  580. $sql .= " LIMIT 1";
  581. $this->execute($sql);
  582. return $this->fetch();
  583. }
  584.  
  585. public function findAllBySql($sql){
  586. $rows = array();
  587. $this->execute($sql);
  588. while($row = $this->fetch()){
  589. $rows[] = $row;
  590. }
  591. return $rows;
  592. }
  593.  
  594. public function findByPk($table,$_pk){
  595. $pk = $this->getPk($table);
  596. if($pk == null){
  597. $this->errorMsg = "未找到该表的主键";
  598. return false;
  599. }else{
  600. return $this->find($table,array(
  601. $pk => $_pk
  602. ));
  603. }
  604. }
  605.  
  606. public function deleteByPk($table,$_pk){
  607. $pk = $this->getPk($table);
  608. if($pk == null){
  609. $this->errorMsg = "未找到该表的主键";
  610. return false;
  611. }else{
  612. $sql = "DELETE FROM ".$table." WHERE `{$pk}`='{$_pk}'";
  613. return $this->delete($table,array(
  614. $pk => $_pk
  615. ));
  616. }
  617. }
  618.  
  619. }
  620. /*
  621. * 类库更新日志 2013.5.25
  622. * 1、update delete操作中的条件可以设置为数组形式$key=>$value
  623. * 2、增加事务处理功能(只针对innodb引擎)
  624. * 3、增加根据条件查找一条记录
  625. * 4、增加根据条件查找所有记录
  626. * 5、增加根据主键查找记录
  627. * 6、增加根据主键删除记录
  628. */
  629. ?>

mysql操作类库--摘抄的更多相关文章

  1. ecshop的Mysql操作类

    摘要,这是直接摘抄的ecshop的mysql操作类:不过他这里的缓存是用的文件缓存,我们如果想直接使用,可以替换成memcache的或者redis的! <?php /** * ECSHOP MY ...

  2. Mysql操作初级

    Mysql操作初级 本节内容 数据库概述 数据库安装 数据库操作 数据表操作 表内容操作 1.数据库概述 数据库管理系统叫做DBMS 1.什么是数据库 ? 答:数据的仓库,如:在ATM的示例中我们创建 ...

  3. python学习道路(day12note)(mysql操作,python链接mysql,redis)

    1,针对mysql操作 SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpass'); 设置密码 update user set password ...

  4. 学习笔记:MySQL操作初步

    对数据库的操作:SQL语言 一:SQL:Structured Query Language,结构化查询语言! 二:DDL:Data Definition Language,数据定义语言 三:DML:D ...

  5. shell执行mysql操作

    http://ully.iteye.com/blog/1226494 http://www.jb51.net/article/55207.htm shell执行mysql操作 mysql  -hhos ...

  6. 第一篇:Mysql操作初级

    Mysql操作初级   Mysql操作初级 本节内容 数据库概述 数据库安装 数据库操作 数据表操作 表内容操作 1.数据库概述 数据库管理系统叫做DBMS 1.什么是数据库 ? 答:数据的仓库,如: ...

  7. Mysql 操作手册

    mysql操作手册 版本:5.6.16mysql linux安装基本步骤:#rpm -e --nodeps mysql-lib-5.1.*#rpm -ivh mysql-server#rpm -ivh ...

  8. Python 第九篇:队列Queue、生产者消费者模型、(IO/异步IP/Select/Poll/Epool)、Mysql操作

    Mysql操作: grant select,insert,update,delete on *.* to root@"%" Identified by "123456&q ...

  9. FtpHelper ftp操作类库

    FtpHelper ftp操作类库 using System; using System.Collections.Generic; using System.Linq; using System.Te ...

随机推荐

  1. wp8 入门到精通 线程

    Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format("A push notification {0} error oc ...

  2. Android项目环境搭建

    安装步骤: ①     安装JDK1.6 在Windows上配置Java环境变量 # JAVA_HOME(C:\Program Files\Java\jdk1.6.0_06),Path(C:\Prog ...

  3. BestCoder 1st Anniversary B.Hidden String DFS

    B. Hidden String Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://bestcoder.hdu.edu.cn/contests/co ...

  4. zookeeper 4 letter 描述与实践

    命令示例描述 Conf echo conf | nc localhost 2181 (New in 3.3.0)输出相关服务配置的详细信息.比如端口.zk数据及日志配置路径.最大连接数,session ...

  5. Dialog对话框

    1.显示内容 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(&q ...

  6. IE下Checkbox标签的onchange事件兼容

    Checkbox onchange事件在谷歌上ok,在ie8上不起作用了. 一番周折,测试发现勾选了以后还要点击其他位置才会触发onchange事件. 用度娘查询了一下. 有下面两种解决方式: 用on ...

  7. Xamarin.Android模拟器提示HAX kernel module is not Installed

    Xamarin.Android模拟器提示HAX kernel module is not Installed 错误信息:emulator : ERROR : x86 emulation current ...

  8. 简单几何(求交点) UVA 11437 Triangle Fun

    题目传送门 题意:三角形三等分点连线组成的三角形面积 分析:入门题,先求三等分点,再求交点,最后求面积.还可以用梅涅劳斯定理来做 /********************************** ...

  9. 三十分钟掌握STL

    这是本小人书.原名是<using stl>,不知道是谁写的.不过我倒觉得很有趣,所以化了两个晚上把它翻译出来.我没有对翻译出来的内容校验过.如果你没法在三十分钟内觉得有所收获,那么赶紧扔了 ...

  10. Spark Streaming实时计算框架介绍

    随着大数据的发展,人们对大数据的处理要求也越来越高,原有的批处理框架MapReduce适合离线计算,却无法满足实时性要求较高的业务,如实时推荐.用户行为分析等. Spark Streaming是建立在 ...