Mysql.class.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace Think\Db\Driver;
  12. use Think\Db\Driver;
  13. /**
  14. * mysql数据库驱动
  15. */
  16. class Mysql extends Driver{
  17. /**
  18. * 解析pdo连接的dsn信息
  19. * @access public
  20. * @param array $config 连接信息
  21. * @return string
  22. */
  23. protected function parseDsn($config){
  24. $dsn = 'mysql:dbname='.$config['database'].';host='.$config['hostname'];
  25. if(!empty($config['hostport'])) {
  26. $dsn .= ';port='.$config['hostport'];
  27. }elseif(!empty($config['socket'])){
  28. $dsn .= ';unix_socket='.$config['socket'];
  29. }
  30. if(!empty($config['charset'])){
  31. //为兼容各版本PHP,用两种方式设置编码
  32. $this->options[\PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES '.$config['charset'];
  33. $dsn .= ';charset='.$config['charset'];
  34. }
  35. return $dsn;
  36. }
  37. /**
  38. * 取得数据表的字段信息
  39. * @access public
  40. */
  41. public function getFields($tableName) {
  42. $this->initConnect(true);
  43. list($tableName) = explode(' ', $tableName);
  44. if(strpos($tableName,'.')){
  45. list($dbName,$tableName) = explode('.',$tableName);
  46. $sql = 'SHOW COLUMNS FROM `'.$dbName.'`.`'.$tableName.'`';
  47. }else{
  48. $sql = 'SHOW COLUMNS FROM `'.$tableName.'`';
  49. }
  50. $result = $this->query($sql);
  51. $info = array();
  52. if($result) {
  53. foreach ($result as $key => $val) {
  54. if(\PDO::CASE_LOWER != $this->_linkID->getAttribute(\PDO::ATTR_CASE)){
  55. $val = array_change_key_case ( $val , CASE_LOWER );
  56. }
  57. $info[$val['field']] = array(
  58. 'name' => $val['field'],
  59. 'type' => $val['type'],
  60. 'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes
  61. 'default' => $val['default'],
  62. 'primary' => (strtolower($val['key']) == 'pri'),
  63. 'autoinc' => (strtolower($val['extra']) == 'auto_increment'),
  64. );
  65. }
  66. }
  67. return $info;
  68. }
  69. /**
  70. * 取得数据库的表信息
  71. * @access public
  72. */
  73. public function getTables($dbName='') {
  74. $sql = !empty($dbName)?'SHOW TABLES FROM '.$dbName:'SHOW TABLES ';
  75. $result = $this->query($sql);
  76. $info = array();
  77. foreach ($result as $key => $val) {
  78. $info[$key] = current($val);
  79. }
  80. return $info;
  81. }
  82. /**
  83. * 字段和表名处理
  84. * @access protected
  85. * @param string $key
  86. * @return string
  87. */
  88. protected function parseKey(&$key) {
  89. $key = trim($key);
  90. if(!is_numeric($key) && !preg_match('/[,\'\"\*\(\)`.\s]/',$key)) {
  91. $key = '`'.$key.'`';
  92. }
  93. return $key;
  94. }
  95. /**
  96. * 批量插入记录
  97. * @access public
  98. * @param mixed $dataSet 数据集
  99. * @param array $options 参数表达式
  100. * @param boolean $replace 是否replace
  101. * @return false | integer
  102. */
  103. public function insertAll($dataSet,$options=array(),$replace=false) {
  104. $values = array();
  105. $this->model = $options['model'];
  106. if(!is_array($dataSet[0])) return false;
  107. $this->parseBind(!empty($options['bind'])?$options['bind']:array());
  108. $fields = array_map(array($this,'parseKey'),array_keys($dataSet[0]));
  109. foreach ($dataSet as $data){
  110. $value = array();
  111. foreach ($data as $key=>$val){
  112. if(is_array($val) && 'exp' == $val[0]){
  113. $value[] = $val[1];
  114. }elseif(is_null($val)){
  115. $value[] = 'NULL';
  116. }elseif(is_scalar($val)){
  117. if(0===strpos($val,':') && in_array($val,array_keys($this->bind))){
  118. $value[] = $this->parseValue($val);
  119. }else{
  120. $name = count($this->bind);
  121. $value[] = ':'.$name;
  122. $this->bindParam($name,$val);
  123. }
  124. }
  125. }
  126. $values[] = '('.implode(',', $value).')';
  127. }
  128. // 兼容数字传入方式
  129. $replace= (is_numeric($replace) && $replace>0)?true:$replace;
  130. $sql = (true===$replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES '.implode(',',$values).$this->parseDuplicate($replace);
  131. $sql .= $this->parseComment(!empty($options['comment'])?$options['comment']:'');
  132. return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);
  133. }
  134. /**
  135. * ON DUPLICATE KEY UPDATE 分析
  136. * @access protected
  137. * @param mixed $duplicate
  138. * @return string
  139. */
  140. protected function parseDuplicate($duplicate){
  141. // 布尔值或空则返回空字符串
  142. if(is_bool($duplicate) || empty($duplicate)) return '';
  143. if(is_string($duplicate)){
  144. // field1,field2 转数组
  145. $duplicate = explode(',', $duplicate);
  146. }elseif(is_object($duplicate)){
  147. // 对象转数组
  148. $duplicate = get_class_vars($duplicate);
  149. }
  150. $updates = array();
  151. foreach((array) $duplicate as $key=>$val){
  152. if(is_numeric($key)){ // array('field1', 'field2', 'field3') 解析为 ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), field3=VALUES(field3)
  153. $updates[] = $this->parseKey($val)."=VALUES(".$this->parseKey($val).")";
  154. }else{
  155. if(is_scalar($val)) // 兼容标量传值方式
  156. $val = array('value', $val);
  157. if(!isset($val[1])) continue;
  158. switch($val[0]){
  159. case 'exp': // 表达式
  160. $updates[] = $this->parseKey($key)."=($val[1])";
  161. break;
  162. case 'value': // 值
  163. default:
  164. $name = count($this->bind);
  165. $updates[] = $this->parseKey($key)."=:".$name;
  166. $this->bindParam($name, $val[1]);
  167. break;
  168. }
  169. }
  170. }
  171. if(empty($updates)) return '';
  172. return " ON DUPLICATE KEY UPDATE ".join(', ', $updates);
  173. }
  174. /**
  175. * 执行存储过程查询 返回多个数据集
  176. * @access public
  177. * @param string $str sql指令
  178. * @param boolean $fetchSql 不执行只是获取SQL
  179. * @return mixed
  180. */
  181. public function procedure($str,$fetchSql=false) {
  182. $this->initConnect(false);
  183. $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
  184. if ( !$this->_linkID ) return false;
  185. $this->queryStr = $str;
  186. if($fetchSql){
  187. return $this->queryStr;
  188. }
  189. //释放前次的查询结果
  190. if ( !empty($this->PDOStatement) ) $this->free();
  191. $this->queryTimes++;
  192. N('db_query',1); // 兼容代码
  193. // 调试开始
  194. $this->debug(true);
  195. $this->PDOStatement = $this->_linkID->prepare($str);
  196. if(false === $this->PDOStatement){
  197. $this->error();
  198. return false;
  199. }
  200. try{
  201. $result = $this->PDOStatement->execute();
  202. // 调试结束
  203. $this->debug(false);
  204. do
  205. {
  206. $result = $this->PDOStatement->fetchAll(\PDO::FETCH_ASSOC);
  207. if ($result)
  208. {
  209. $resultArr[] = $result;
  210. }
  211. }
  212. while ($this->PDOStatement->nextRowset());
  213. $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, $this->options[\PDO::ATTR_ERRMODE]);
  214. return $resultArr;
  215. }catch (\PDOException $e) {
  216. $this->error();
  217. $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, $this->options[\PDO::ATTR_ERRMODE]);
  218. return false;
  219. }
  220. }
  221. }