Mysql.class.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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_scalar($val)){
  115. if(0===strpos($val,':') && in_array($val,array_keys($this->bind))){
  116. $value[] = $this->parseValue($val);
  117. }else{
  118. $name = count($this->bind);
  119. $value[] = ':'.$name;
  120. $this->bindParam($name,$val);
  121. }
  122. }
  123. }
  124. $values[] = '('.implode(',', $value).')';
  125. }
  126. // 兼容数字传入方式
  127. $replace= (is_numeric($replace) && $replace>0)?true:$replace;
  128. $sql = (true===$replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES '.implode(',',$values).$this->parseDuplicate($replace);
  129. $sql .= $this->parseComment(!empty($options['comment'])?$options['comment']:'');
  130. return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);
  131. }
  132. /**
  133. * ON DUPLICATE KEY UPDATE 分析
  134. * @access protected
  135. * @param mixed $duplicate
  136. * @return string
  137. */
  138. protected function parseDuplicate($duplicate){
  139. // 布尔值或空则返回空字符串
  140. if(is_bool($duplicate) || empty($duplicate)) return '';
  141. if(is_string($duplicate)){
  142. // field1,field2 转数组
  143. $duplicate = explode(',', $duplicate);
  144. }elseif(is_object($duplicate)){
  145. // 对象转数组
  146. $duplicate = get_class_vars($duplicate);
  147. }
  148. $updates = array();
  149. foreach((array) $duplicate as $key=>$val){
  150. if(is_numeric($key)){ // array('field1', 'field2', 'field3') 解析为 ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), field3=VALUES(field3)
  151. $updates[] = $this->parseKey($val)."=VALUES(".$this->parseKey($val).")";
  152. }else{
  153. if(is_scalar($val)) // 兼容标量传值方式
  154. $val = array('value', $val);
  155. if(!isset($val[1])) continue;
  156. switch($val[0]){
  157. case 'exp': // 表达式
  158. $updates[] = $this->parseKey($key)."=($val[1])";
  159. break;
  160. case 'value': // 值
  161. default:
  162. $name = count($this->bind);
  163. $updates[] = $this->parseKey($key)."=:".$name;
  164. $this->bindParam($name, $val[1]);
  165. break;
  166. }
  167. }
  168. }
  169. if(empty($updates)) return '';
  170. return " ON DUPLICATE KEY UPDATE ".join(', ', $updates);
  171. }
  172. }