Mysql.class.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. if(version_compare(PHP_VERSION,'5.3.6','<')){
  32. // PHP5.3.6以下不支持charset设置
  33. $this->options[\PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES '.$config['charset'];
  34. }else{
  35. $dsn .= ';charset='.$config['charset'];
  36. }
  37. }
  38. return $dsn;
  39. }
  40. /**
  41. * 取得数据表的字段信息
  42. * @access public
  43. */
  44. public function getFields($tableName) {
  45. $this->initConnect(true);
  46. list($tableName) = explode(' ', $tableName);
  47. $sql = 'SHOW COLUMNS FROM `'.$tableName.'`';
  48. $result = $this->query($sql);
  49. $info = array();
  50. if($result) {
  51. foreach ($result as $key => $val) {
  52. if(\PDO::CASE_LOWER != $this->_linkID->getAttribute(\PDO::ATTR_CASE)){
  53. $val = array_change_key_case ( $val , CASE_LOWER );
  54. }
  55. $info[$val['field']] = array(
  56. 'name' => $val['field'],
  57. 'type' => $val['type'],
  58. 'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes
  59. 'default' => $val['default'],
  60. 'primary' => (strtolower($val['key']) == 'pri'),
  61. 'autoinc' => (strtolower($val['extra']) == 'auto_increment'),
  62. );
  63. }
  64. }
  65. return $info;
  66. }
  67. /**
  68. * 取得数据库的表信息
  69. * @access public
  70. */
  71. public function getTables($dbName='') {
  72. $sql = !empty($dbName)?'SHOW TABLES FROM '.$dbName:'SHOW TABLES ';
  73. $result = $this->query($sql);
  74. $info = array();
  75. foreach ($result as $key => $val) {
  76. $info[$key] = current($val);
  77. }
  78. return $info;
  79. }
  80. /**
  81. * 字段和表名处理
  82. * @access protected
  83. * @param string $key
  84. * @return string
  85. */
  86. protected function parseKey(&$key) {
  87. $key = trim($key);
  88. if(!is_numeric($key) && !preg_match('/[,\'\"\*\(\)`.\s]/',$key)) {
  89. $key = '`'.$key.'`';
  90. }
  91. return $key;
  92. }
  93. /**
  94. * 批量插入记录
  95. * @access public
  96. * @param mixed $dataSet 数据集
  97. * @param array $options 参数表达式
  98. * @param boolean $replace 是否replace
  99. * @return false | integer
  100. */
  101. public function insertAll($dataSet,$options=array(),$replace=false) {
  102. $values = array();
  103. $this->model = $options['model'];
  104. if(!is_array($dataSet[0])) return false;
  105. $this->parseBind(!empty($options['bind'])?$options['bind']:array());
  106. $fields = array_map(array($this,'parseKey'),array_keys($dataSet[0]));
  107. foreach ($dataSet as $data){
  108. $value = array();
  109. foreach ($data as $key=>$val){
  110. if(is_array($val) && 'exp' == $val[0]){
  111. $value[] = $val[1];
  112. }elseif(is_scalar($val)){
  113. if(0===strpos($val,':') && in_array($val,array_keys($this->bind))){
  114. $value[] = $this->parseValue($val);
  115. }else{
  116. $name = count($this->bind);
  117. $value[] = ':'.$name;
  118. $this->bindParam($name,$val);
  119. }
  120. }
  121. }
  122. $values[] = '('.implode(',', $value).')';
  123. }
  124. // 兼容数字传入方式
  125. $replace= (is_numeric($replace) && $replace>0)?true:$replace;
  126. $sql = (true===$replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES '.implode(',',$values).$this->parseDuplicate($replace);
  127. $sql .= $this->parseComment(!empty($options['comment'])?$options['comment']:'');
  128. return $this->execute($sql,!empty($options['fetch_sql']) ? true : false);
  129. }
  130. /**
  131. * ON DUPLICATE KEY UPDATE 分析
  132. * @access protected
  133. * @param mixed $duplicate
  134. * @return string
  135. */
  136. protected function parseDuplicate($duplicate){
  137. // 布尔值或空则返回空字符串
  138. if(is_bool($duplicate) || empty($duplicate)) return '';
  139. // field1,field2 转数组
  140. if(is_string($duplicate)) $duplicate = explode(',', $duplicate);
  141. // 对象转数组
  142. if(is_object($duplicate)) $duplicate = get_class_vars($duplicate);
  143. $updates = array();
  144. foreach((array) $duplicate as $key=>$val){
  145. if(is_numeric($key)){ // array('field1', 'field2', 'field3') 解析为 ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), field3=VALUES(field3)
  146. $updates[] = $this->parseKey($val)."=VALUES(".$this->parseKey($val).")";
  147. }else{
  148. if(is_scalar($val)) // 兼容标量传值方式
  149. $val = array('value', $val);
  150. if(!isset($val[1])) continue;
  151. switch($val[0]){
  152. case 'exp': // 表达式
  153. $updates[] = $this->parseKey($key)."=($val[1])";
  154. break;
  155. case 'value': // 值
  156. default:
  157. $name = count($this->bind);
  158. $updates[] = $this->parseKey($key)."=:".$name;
  159. $this->bindParam($name, $val[1]);
  160. break;
  161. }
  162. }
  163. }
  164. if(empty($updates)) return '';
  165. return " ON DUPLICATE KEY UPDATE ".join(', ', $updates);
  166. }
  167. }