Base.php 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. <?php
  2. namespace Qii\Driver;
  3. class Base
  4. {
  5. const VERSION = '1.2';
  6. public $cache;
  7. public $language;
  8. protected $_query = array(
  9. "INSERT" => "INSERT INTO %s(%s) VALUES('%s')",
  10. "REPLACE" => "REPLACE %s (%s) VALUES('%s')",
  11. "SELECT" => "SELECT %s FROM %s",
  12. "LEFT_JOIN" => " LEFT JOIN %s ON %s",
  13. "RIGHT_JOIN" => " RIGHT JOIN %s ON %s",
  14. "UPDATE" => "UPDATE %s SET ",
  15. "DELETE" => "DELETE FROM %s %s",
  16. "WHERE" => " WHERE %s",
  17. "LIKE" => " `%s` LIKE '%s'",
  18. "ORDER" => " ORDER BY %s %s",
  19. "GROUP" => " GROUP BY %s",
  20. "LIMIT" => " LIMIT %d, %d"
  21. );
  22. private $query;
  23. private $setArray = array();
  24. public $modelSQL = "";
  25. protected $fields;
  26. protected $groupBy;
  27. protected $limit;
  28. protected $orderBy;
  29. public $load;
  30. public $where = null;
  31. public $join = null;
  32. /**
  33. * @var string $response Response对象
  34. */
  35. public $response;
  36. //方法对应的别名
  37. protected $_modelAlias = array('selectRows' => 'selectAll', 'select' => 'selectRow', 'getOne' => 'selectOne', 'getRow' => 'selectRow', 'getAll' => 'selectAll', 'remove' => 'deleteRows');
  38. public function __construct()
  39. {
  40. $this->language = \Qii\Autoloader\Psr4::getInstance()->loadClass('Qii\Language\Loader');
  41. $this->load = \Qii\Autoloader\Psr4::getInstance()->loadClass('\Qii\Autoloader\Loader');
  42. $this->response = new \Qii\Driver\Response();
  43. }
  44. /**
  45. * 获取数据库中所有的数据表
  46. * @return array
  47. */
  48. public function getAllDatabases()
  49. {
  50. $sql = "SHOW DATABASES";
  51. $rs = $this->setQuery($sql);
  52. $database = array();
  53. while ($row = $rs->fetch()) {
  54. $database[] = $row['Database'];
  55. }
  56. return $database;
  57. }
  58. /**
  59. * 数据库中是否包含指定库
  60. * @param string $database 数据库名
  61. * @return bool
  62. */
  63. public function hasDatabase($database)
  64. {
  65. if (!$database) return false;
  66. $sql = "SHOW DATABASES LIKE '" . $database . "'";
  67. $rs = $this->setQuery($sql);
  68. while ($row = $rs->fetch()) {
  69. $val = array_values($row);
  70. if (in_array($database, $val)) {
  71. return true;
  72. }
  73. }
  74. return false;
  75. }
  76. /**
  77. * 获取当前数据库中所有的表
  78. * @param null|string $database 数据库
  79. * @return array
  80. */
  81. public function getAllTables($database = null)
  82. {
  83. if ($database) {
  84. $this->setQuery('USE ' . $database);
  85. }
  86. $sql = "SHOW TABLES";
  87. $rs = $this->setQuery($sql);
  88. $tables = array();
  89. while ($row = $rs->fetch()) {
  90. if (is_array($row)) {
  91. foreach ($row AS $val) {
  92. $tables[] = $val;
  93. }
  94. }
  95. }
  96. return $tables;
  97. }
  98. /**
  99. * 获取指定数据表的所有字段
  100. * @param string $table 表名
  101. * @param string $database 数据库名
  102. * @param string $autoIncr 自动增长的序号
  103. * @return array
  104. */
  105. public function getTableInfo($table, $database = null, $autoIncr = null)
  106. {
  107. if (!$database) $database = $this->currentDB;
  108. $sql = "SELECT * from information_schema.COLUMNS where table_name = '" . $table . "' and table_schema = '" . $database . "'";
  109. $data = ['fields' => [],
  110. 'rules' => [
  111. 'pri' => [], 'required' => []
  112. ]
  113. ];
  114. $rs = $this->setQuery($sql);
  115. while ($row = $rs->fetch()) {
  116. $data['fields'][] = $row['COLUMN_NAME'];
  117. if ($row['EXTRA']) {
  118. $data['rules']['extra'][$row['EXTRA']][] = $row['COLUMN_NAME'];
  119. }
  120. if ($row['COLUMN_KEY'] == 'PRI') {
  121. $data['rules']['pri'][] = $row['COLUMN_NAME'];
  122. $data['rules']['required'][] = $row['COLUMN_NAME'];
  123. }
  124. if ($row['IS_NULLABLE'] == 'NO') {
  125. $data['rules']['required'][] = $row['COLUMN_NAME'];
  126. }
  127. if (in_array($row['DATA_TYPE'], ['varchar', 'char'])) {
  128. $data['rules']['maxlength'][$row['COLUMN_NAME']] = $row['CHARACTER_MAXIMUM_LENGTH'];
  129. }
  130. if (in_array($row['DATA_TYPE'], ['mediumtext', 'TINYTEXT', 'text', 'longtext'])) {
  131. $data['rules']['text'][] = $row['COLUMN_NAME'];
  132. }
  133. if (in_array($row['DATA_TYPE'], ['bigint', 'int', 'smallint', 'tinyint', 'integer'])) {
  134. preg_match('/[\d]{1,}/', $row['COLUMN_TYPE'], $matches);
  135. $data['rules']['int'][$row['COLUMN_NAME']] = $matches[0];
  136. $data['rules']['number'][] = $row['COLUMN_NAME'];
  137. }
  138. if (in_array($row['DATA_TYPE'], ['float', 'double', 'decimal'])) {
  139. $data['rules']['float'][$row['COLUMN_NAME']] = $this->getValueFromBrackets($row['COLUMN_TYPE']);
  140. }
  141. if (in_array($row['DATA_TYPE'], ['timestamp', 'datatime'])) {
  142. $data['rules']['timestamp'][] = $row['COLUMN_NAME'];
  143. }
  144. if (in_array($row['DATA_TYPE'], ['enum', 'set'])) {
  145. $data['rules']['sets'][$row['COLUMN_NAME']] = $this->getValueFromBrackets($row['COLUMN_TYPE']);
  146. }
  147. if (isset($row['COLUMN_DEFAULT'])) {
  148. $data['rules']['default'][$row['COLUMN_NAME']] = $row['COLUMN_DEFAULT'];
  149. }
  150. }
  151. $data['sql'] = $this->getTableSQL($table, $database, $autoIncr);
  152. return $data;
  153. }
  154. /**
  155. * 从括号中获取指定的值
  156. * @param string $str 需要获取的内容
  157. * @return array
  158. */
  159. public function getValueFromBrackets($str)
  160. {
  161. preg_match("/(?:\()(.*)(?:\))/i", $str, $matches);
  162. $str = $matches[1];
  163. $a = explode(",", $str);
  164. for ($i = 0; $i < count($a); $i++) {
  165. $this->removeQuote($a[$i]);//从字符串中去除单引号
  166. }
  167. return $a;
  168. }
  169. /**
  170. * 去除双引号
  171. * @param string $str 去除双引号
  172. */
  173. public function removeQuote(&$str)
  174. {
  175. if (preg_match("/^\'/", $str)) {
  176. $str = substr($str, 1, strlen($str) - 1);
  177. }
  178. if (preg_match("/\'$/", $str)) {
  179. $str = substr($str, 0, strlen($str) - 1);
  180. }
  181. return $str;
  182. }
  183. /**
  184. * 查询数据库中是否有指定的表
  185. * @param string $tableName 表名
  186. * @param null|string $database 数据库
  187. * @return bool
  188. */
  189. public function hasTable($tableName, $database = null)
  190. {
  191. if ($database) {
  192. $this->setQuery('USE ' . $database);
  193. }
  194. $sql = "SHOW TABLES LIKE '" . $tableName . "'";
  195. $rs = $this->setQuery($sql);
  196. $tables = array();
  197. while ($row = $this->fetch($rs)) {
  198. if (is_array($row)) {
  199. foreach ($row AS $val) {
  200. if ($val == $tableName) return true;
  201. }
  202. }
  203. }
  204. return false;
  205. }
  206. /**
  207. * 获取创建表的SQL语句
  208. * @param string $tableName 表名
  209. * @param null|string $database 数据库
  210. * @param int|null $autoIncr 自增长的值,null的话就不使用
  211. * @return string
  212. */
  213. public function getTableSQL($tableName, $database = null, $autoIncr = null)
  214. {
  215. if ($database) {
  216. $this->setQuery('USE ' . $database);
  217. }
  218. $row = $this->getRow("SHOW CREATE TABLE `" . $tableName . "`");
  219. if (!$row) {
  220. throw new \Exception('数据表不存在', __LINE__);
  221. }
  222. $sql = $row['Create Table'];
  223. if ($autoIncr === null) {
  224. return $sql;
  225. }
  226. return preg_replace("/AUTO_INCREMENT=[\d]{1,}/", "AUTO_INCREMENT=" . intval($autoIncr), $sql);
  227. }
  228. /**
  229. * 通过数据表名称获取规则
  230. * @param string $table 表名
  231. * @param string $database 数据库名
  232. */
  233. public function buildRulesForTable($table, $database = null)
  234. {
  235. if (!$database) $database = $this->currentDB;
  236. $tableInfo = $this->getTableInfo($table, $database);
  237. $rules = new \Qii\Base\Rules();
  238. $rules->addFields($tableInfo['fields']);
  239. if ($tableInfo['rules']['required']) {
  240. $rules->addForceValidKey($tableInfo['rules']['required']);
  241. }
  242. if (isset($tableInfo['rules']['number'])) {
  243. foreach ($tableInfo['rules']['number'] as $key => $value) {
  244. $rules->addRules($value, 'number', true, $value . '字段必须是数字');
  245. }
  246. }
  247. if (isset($tableInfo['rules']['maxlength'])) {
  248. foreach ($tableInfo['rules']['maxlength'] as $key => $value) {
  249. $rules->addRules($key, 'maxlength', $value, $key . '字段内容长度不能大于' . $value . '个字符');
  250. }
  251. }
  252. if (isset($tableInfo['rules']['timestamp'])) {
  253. foreach ($tableInfo['rules']['timestamp'] as $key => $value) {
  254. $rules->addRules($value, 'datetime', true, $value . '字段必须为日期格式');
  255. }
  256. }
  257. return $rules;
  258. }
  259. final public function getAlias($alias)
  260. {
  261. return isset($this->_modelAlias[$alias]) ? $this->_modelAlias[$alias] : null;
  262. }
  263. /**
  264. * 设置Cache
  265. *
  266. * @param String $cache
  267. * @param Array $policy
  268. */
  269. final public function setCache($cache, $policy)
  270. {
  271. \Qii\Autoloader\Import::requires(Qii_DIR . DS . 'Qii' . DS . 'Cache.php');
  272. $this->cache = \Qii\Autoloader\Psr4::loadClass('\Qii\Cache', $cache)->initialization($policy);//载入cache类文件
  273. }
  274. /**
  275. * 缓存内容
  276. *
  277. * @param String $id
  278. * @param Array $value
  279. * @return Bool
  280. */
  281. final public function cache($id, $value)
  282. {
  283. return $this->cache->set($id, $value);
  284. }
  285. /**
  286. * 获取缓存的类
  287. */
  288. final public function getCache()
  289. {
  290. return $this->cache;
  291. }
  292. /**
  293. * 获取缓存内容
  294. *
  295. * @param String $id
  296. * @return Array
  297. */
  298. final public function getCacheData($id)
  299. {
  300. return $this->cache->get($id);
  301. }
  302. /**
  303. * 获取表的名称
  304. * @param String $table
  305. * @return String
  306. */
  307. public function getTable($table)
  308. {
  309. list($database, $tableName) = array_pad(explode('.', $table), 2, '');
  310. if ($tableName) {
  311. $tableName = stristr($tableName, '`') ? $tableName : '`'. $tableName .'`';
  312. return "`{$database}`.`{$tableName}`";
  313. }
  314. $table = stristr($table, '`') ? $table : '`'. $table .'`';
  315. return $table;
  316. }
  317. public function setLanguage()
  318. {
  319. $this->language = \Qii\Autoloader\Psr4::loadClass('Qii\Language\Loader');
  320. }
  321. /**
  322. *
  323. * Insert Object
  324. * @param String $table
  325. * @param Array|Object $dataArray
  326. */
  327. final function insertObject($table, $dataArray)
  328. {
  329. if (empty($table)) {
  330. return -1;
  331. }
  332. if (sizeof($dataArray) > 0 || (is_object($dataArray) && get_object_vars($dataArray)) > 0) {
  333. $keys = array();
  334. $values = array();
  335. foreach ($dataArray AS $key => $value) {
  336. $keys[] = $key;
  337. if (is_array($value)) {
  338. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  339. }
  340. $values[] = $this->setQuote($value);
  341. }
  342. $this->modelSQL = $sql = "INSERT INTO " . $this->getTable($table) . "(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
  343. $this->setQuery($sql);
  344. $this->cleanData();
  345. $this->setError();
  346. return $this->lastInsertId();
  347. }
  348. return -2;
  349. }
  350. /**
  351. * 左连表
  352. *
  353. * @param string $table 表名
  354. * @param string $on on条件
  355. * @return $this
  356. */
  357. final function leftJoinObject($table, $on)
  358. {
  359. if(empty($table) || empty($on)) return $this;
  360. $this->join .= sprintf($this->_query['LEFT_JOIN'], $table, $on);
  361. return $this;
  362. }
  363. /**
  364. * 右连表
  365. *
  366. * @param string $table 表名
  367. * @param string $on on条件
  368. * @return $this
  369. */
  370. final function rightJoinObject($table, $on)
  371. {
  372. if(empty($table) || empty($on)) return $this;
  373. $this->join .= sprintf($this->_query['RIGHT_JOIN'], $table, $on);
  374. return $this;
  375. }
  376. /**
  377. *
  378. * Replace Object
  379. * @param String $table
  380. * @param Array|Object $dataArray
  381. */
  382. final function replaceObject($table, $dataArray)
  383. {
  384. if (empty($table)) {
  385. return -1;
  386. }
  387. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  388. $keys = array();
  389. $values = array();
  390. foreach ($dataArray AS $key => $value) {
  391. $keys[] = $key;
  392. if (is_array($value)) {
  393. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  394. }
  395. $values[] = $this->setQuote($value);
  396. }
  397. $this->modelSQL = $sql = "REPLACE INTO " . $this->getTable($table) . "(`" . join("`, `", $keys) . "`) VALUES('" . join("', '", $values) . "')";
  398. $rs = $this->setQuery($sql);
  399. $this->cleanData();
  400. $this->setError();
  401. return $this->AffectedRows($rs);
  402. }
  403. return -2;
  404. }
  405. /**
  406. *
  407. * Update data
  408. * @param String $table
  409. * @param Array|Objct $dataArray
  410. * @param Array $keys
  411. */
  412. final function updateObject($table, $dataArray, $keys = array())
  413. {
  414. if (empty($table) || !is_array($keys)) {
  415. return -1;
  416. }
  417. if (sizeof($dataArray) > 0 || get_object_vars($dataArray) > 0) {
  418. $values = array();
  419. $where = array();
  420. foreach ($dataArray AS $key => $value) {
  421. if (is_array($value)) {
  422. throw new \Qii\Exceptions\InvalidFormat(_i('Invalid %s format', $key), __LINE__);
  423. }
  424. $value = $this->setQuote($value);
  425. if (in_array($key, $keys)) {
  426. $where[] = "`{$key}` = '" . $value . "'";
  427. } else {
  428. $values[] = "`{$key}` = '" . $value . "'";
  429. }
  430. }
  431. //$keys为key => value的方式,就直接用keys
  432. if (empty($where) && count($keys) > 0) {
  433. foreach ($keys as $key => $value) {
  434. $value = $this->setQuote($value);
  435. $where[] = "`{$key}` = '" . $value . "'";
  436. }
  437. }
  438. $whereSQL = $this->where;
  439. if (sizeof($where) > 0) {
  440. $whereSQL = $this->where ? $this->where . " AND (" . join(" AND ", $where) . ")" : " WHERE " . join(" AND ", $where);
  441. }
  442. $this->modelSQL = $sql = "UPDATE " . $this->getTable($table) . " SET " . join(", ", $values) . $whereSQL;
  443. $rs = $this->setQuery($sql);
  444. $this->cleanData();
  445. $this->setError();
  446. return $this->AffectedRows($rs);
  447. }
  448. return 0;
  449. }
  450. /**
  451. *
  452. * 删除数据
  453. * @param String $table
  454. * @param Array $keys
  455. */
  456. final function deleteObject($table, $keys = array())
  457. {
  458. if (empty($table)) {
  459. return -1;
  460. }
  461. $where = array();
  462. if (sizeof($keys) > 0 || (is_a($keys, 'stdclass') && get_object_vars($keys))) {
  463. foreach ($keys AS $k => $v) {
  464. $where[] = "`{$k}` = '" . $this->setQuote($v) . "'";
  465. }
  466. }
  467. $whereSQL = $this->where;
  468. if (sizeof($where) > 0) {
  469. $whereSQL = $this->where ? $this->where . " AND (" . join(" AND ", $where) . ")" : " WHERE " . join(" AND ", $where);
  470. }
  471. $this->modelSQL = $sql = "DELETE FROM " . $this->getTable($table) . " " . $whereSQL;
  472. $rs = $this->query($sql);
  473. $this->cleanData();
  474. $this->setError();
  475. return $this->AffectedRows($rs);
  476. }
  477. /**
  478. * 需要清除的数据
  479. *
  480. * @return array
  481. */
  482. final function cleanOptions()
  483. {
  484. return array('fields', 'where', 'groupBy', 'orderBy', 'limit', 'setArray', 'join');
  485. }
  486. /**
  487. * 清除数据
  488. *
  489. */
  490. final function cleanData()
  491. {
  492. $array = $this->cleanOptions();
  493. foreach ($array AS $k) {
  494. if (is_array($this->$k)) {
  495. $this->$k = array();
  496. } else {
  497. $this->$k = null;
  498. }
  499. }
  500. }
  501. /**
  502. *
  503. * 查询的字段
  504. * @param String $fileds
  505. */
  506. final function fields($fileds = "*")
  507. {
  508. $this->fields = null;
  509. if (empty($fileds)) $fileds = "*";
  510. if (is_array($fileds)) $fileds = join(',', $fileds);
  511. $this->fields = $fileds;
  512. return $this;
  513. }
  514. /**
  515. *
  516. * GROUP BY方法
  517. * @param String $fields
  518. */
  519. final function groupBy($fields)
  520. {
  521. $this->groupBy = null;
  522. if (!empty($fields)) {
  523. $fileds = is_array($fields) ? join(', ', $fields) : $fields;
  524. $this->groupBy = sprintf($this->_query['GROUP'], $fields);
  525. }
  526. return $this;
  527. }
  528. /**
  529. *
  530. * 插入数据用
  531. * @param Array $array
  532. */
  533. final function dataArray($array)
  534. {
  535. $this->fileds = null;
  536. if (is_array($array)) {
  537. $tmpArray = array();
  538. foreach ($array AS $k => $v) {
  539. $tmpArray['k'][] = $this->setQuote($k);
  540. $tmpArray['v'][] = $this->setQuote($v);
  541. }
  542. $this->fileds = $tmpArray;
  543. }
  544. return $this;
  545. }
  546. /**
  547. *
  548. * Order By函数
  549. * @param String $field
  550. * @param String $orderBy
  551. */
  552. final function orderBy($field, $orderBy)
  553. {
  554. if (!empty($field)) return $this;
  555. if ($this->orderBy != '') {
  556. $this->orderBy .= $field . ' ' . $orderBy;
  557. } else {
  558. $this->orderBy = sprintf($this->_query['ORDER'], $field, $orderBy);
  559. }
  560. }
  561. /**
  562. * 多个order by条件
  563. */
  564. final function orderByArr($map)
  565. {
  566. if (empty($map)) return $this;
  567. foreach ($map AS $val) {
  568. $this->orderBy($val['field'], $val['orderBy']);
  569. }
  570. return $this;
  571. }
  572. /**
  573. * order by
  574. * @param string order by
  575. */
  576. final function orderByStr($orderBy)
  577. {
  578. if (!$orderBy) return $this;
  579. $this->orderBy = $orderBy;
  580. return $this;
  581. }
  582. /**
  583. *
  584. * Limit函数,如果省略第二个参数则第一个为0,第二个参数值取第一个
  585. * @param Int $limit
  586. * @param Int $offset
  587. */
  588. final function limit($limit, $offset = 0)
  589. {
  590. $this->limit = null;
  591. if ($limit !== '') {
  592. if (!$offset) {
  593. $this->limit = sprintf($this->_query["LIMIT"], 0, $limit);
  594. } else {
  595. $this->limit = sprintf($this->_query["LIMIT"], $limit, $offset);
  596. }
  597. }
  598. return $this;
  599. }
  600. /**
  601. * 创建Like查询条件
  602. * @param string | array $like like的条件
  603. */
  604. final function like($like)
  605. {
  606. if (empty($like)) return $this;
  607. $likeArray = array();
  608. if ($like && !is_array($like)) {
  609. $likeArray[] = $like;
  610. } else {
  611. foreach ($like AS $key => $val) {
  612. if(stristr($key, '.')) {
  613. $likeArray[] = sprintf("%s LIKE '%s'", $key, "%" . $this->setQuote($val) . "%");
  614. }else{
  615. $likeArray[] = sprintf($this->_query['LIKE'], $key, "%" . $this->setQuote($val) . "%");
  616. }
  617. }
  618. }
  619. if (count($likeArray) > 0) {
  620. $likeSQL = join(" OR ", $likeArray);
  621. if (!$this->where) {
  622. $this->where = sprintf($this->_query["WHERE"], $likeSQL);
  623. } else {
  624. $this->where .= ' AND (' . $likeSQL . ')';
  625. }
  626. }
  627. return $this;
  628. }
  629. /**
  630. * 不包含的条件
  631. * @param array $where 条件
  632. * @return $this
  633. */
  634. final function exclude($where)
  635. {
  636. if (empty($where)) return $this;
  637. $whereArray = array();
  638. if ($where && !is_array($where)) {
  639. $whereArray[] = $where;
  640. } else {
  641. foreach ($where AS $key => $val) {
  642. $whereArray[] = sprintf("%s != '%s'", $key, $this->setQuote($val));
  643. }
  644. }
  645. if (count($whereArray) > 0) {
  646. $whereSQL = join(" AND ", $whereArray);
  647. if (!$this->where) {
  648. $this->where = sprintf($this->_query["WHERE"], $whereSQL);
  649. } else {
  650. $this->where .= ' AND (' . $whereSQL . ')';
  651. }
  652. }
  653. return $this;
  654. }
  655. /**
  656. * 传的条件为数组
  657. * @param Array $where 条件
  658. * @return Object 对象本身
  659. */
  660. final function whereArray($where)
  661. {
  662. $this->where = null;
  663. if (!empty($where)) {
  664. $whereArray = array();
  665. foreach ($where AS $k => $v) {
  666. $v = $this->setQuote($v);
  667. if(stristr($k, '.')) {
  668. $whereArray[] = " {$k} = '{$v}'";
  669. }else{
  670. $whereArray[] = " `{$k}` = '{$v}'";
  671. }
  672. }
  673. if (sizeof($whereArray) > 0) {
  674. $whereSQL = join(" AND ", $whereArray);
  675. if (!$this->where) {
  676. $this->where = sprintf($this->_query["WHERE"], $whereSQL);
  677. } else {
  678. $this->where .= " AND (" . $whereSQL . ")";
  679. }
  680. }
  681. }
  682. return $this;
  683. }
  684. /**
  685. *
  686. * WHERE 子句
  687. * @param String $where
  688. */
  689. final function where($where)
  690. {
  691. if (is_array($where)) return $this->whereArray($where);
  692. $this->where = null;
  693. if (!empty($where)) {
  694. $this->where = sprintf($this->_query["WHERE"], $where);
  695. }
  696. return $this;
  697. }
  698. /**
  699. * 创建插入表的SQL
  700. */
  701. final function createInsertSQL($table)
  702. {
  703. $sql = sprintf($this->_query['INSERT'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
  704. $this->cleanData();
  705. return $sql;
  706. }
  707. /**
  708. *
  709. * 插入数据到指定表中
  710. * @param String $table
  711. */
  712. final function insertRow($table)
  713. {
  714. $this->modelSQL = $sql = $this->createInsertSQL($table);
  715. $this->setQuery($sql);
  716. return $this->lastInsertId();
  717. }
  718. /**
  719. * 创建replace object SQL
  720. *
  721. * @param string $table 表名
  722. * @return string
  723. */
  724. final function createReplaceSQL($table)
  725. {
  726. $sql = sprintf($this->_query['REPLACE'], $table, join(",", $this->fileds['k']), join("', '", $this->fileds['v']));
  727. $this->cleanData();
  728. return $sql;
  729. }
  730. /**
  731. *
  732. * Replace方法
  733. * @param String $table
  734. */
  735. final function replaceRow($table)
  736. {
  737. $this->modelSQL = $sql = $this->createReplaceSQL($table);
  738. return $this->exec($sql);
  739. }
  740. /**
  741. *
  742. * 查询一行
  743. * @param String $table
  744. */
  745. final function selectRow($table)
  746. {
  747. $this->modelSQL = $sql = $this->createSelectSQL($table);
  748. $this->cleanData();
  749. return $this->getRow($sql);
  750. }
  751. /**
  752. *
  753. * 查询一行
  754. * @param String $table
  755. */
  756. final function selectOne($table)
  757. {
  758. $this->modelSQL = $sql = $this->createSelectSQL($table);
  759. return $this->getOne($sql);
  760. }
  761. /**
  762. * 创建SELECT SQL
  763. */
  764. final function createSelectSQL($table)
  765. {
  766. if(stristr($table, '.') == false && stristr($table, '`') == false) {
  767. $table = '`'. $table .'`';
  768. }
  769. $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->join . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  770. $this->cleanData();
  771. return $sql;
  772. }
  773. /**
  774. *
  775. * 查询所有
  776. * @param String $table 数据表名称
  777. * @return Array
  778. */
  779. final function selectAll($table)
  780. {
  781. $this->modelSQL = $sql = $this->createSelectSQL($table);
  782. return $this->getAll($sql);
  783. }
  784. /**
  785. * 返回resource资源
  786. * @param string $table 数据表名称
  787. */
  788. final function rs($table)
  789. {
  790. $this->modelSQL = $sql = sprintf($this->_query['SELECT'], ((trim($this->fields) != '') ? $this->fields : "*"), $table) . $this->join . $this->where . $this->groupBy . $this->orderBy . $this->limit;
  791. $this->cleanData();
  792. return $this->setQuery($sql);
  793. }
  794. /**
  795. * 将指定字段减指定值
  796. *
  797. * @param array $data 数据
  798. * @return $this
  799. */
  800. final function downsetCounter($data)
  801. {
  802. if (is_array($data)) {
  803. foreach ($data AS $k => $value) {
  804. $this->setArray[] = $k . "=" . $k . '-' . $value;
  805. }
  806. }
  807. $this->set(null);
  808. return $this;
  809. }
  810. /**
  811. * 将指定字段加指定值
  812. *
  813. * @param $data
  814. * @return $this
  815. */
  816. final function upsetCounter($data)
  817. {
  818. if (is_array($data)) {
  819. foreach ($data AS $k => $value) {
  820. $this->setArray[] = $k . "=" . $k . '+' . $value;
  821. }
  822. }
  823. $this->set(null);
  824. return $this;
  825. }
  826. /**
  827. * 更新数据时候用,方法同setData
  828. * @param Array $data
  829. */
  830. final function set($data)
  831. {
  832. return $this->setData($data);
  833. }
  834. /**
  835. *
  836. * 更新数据时候用
  837. * @param Array $data
  838. * @return $this
  839. */
  840. final function setData($data)
  841. {
  842. if (is_array($data)) {
  843. $set = array();
  844. foreach ($data AS $k => $value) {
  845. $set[] = $k . "='" . $this->setQuote($value) . "'";
  846. }
  847. if (sizeof($this->setArray) > 0) {
  848. $this->set = " " . join(", ", $set) . ", " . join(",", $this->setArray);
  849. } else {
  850. $this->set = " " . join(", ", $set);
  851. }
  852. } else {
  853. if (sizeof($this->setArray) > 0) {
  854. $this->set = join(",", $this->setArray);
  855. } else {
  856. $this->set = "";
  857. }
  858. }
  859. return $this;
  860. }
  861. /**
  862. * 执行更新操作,updateRows的alias
  863. * @param String $table
  864. * @return number
  865. */
  866. /*
  867. final function update($table){
  868. return $this->updateRows($table);
  869. }
  870. */
  871. /**
  872. *
  873. * 执行更新操作
  874. * @param $table
  875. * @return Int 返回影响的行数
  876. */
  877. final function updateRows($table)
  878. {
  879. $this->modelSQL = $sql = sprintf($this->_query['UPDATE'], $table) . $this->set . $this->where . $this->limit;
  880. $this->cleanData();
  881. return $this->exec($sql);
  882. }
  883. /**
  884. *
  885. * 执行删除操作
  886. * @param String $table
  887. */
  888. final function deleteRows($table)
  889. {
  890. $this->modelSQL = $sql = sprintf($this->_query['DELETE'], $table, $this->where) . $this->limit;
  891. $this->cleanData();
  892. return $this->exec($sql);
  893. }
  894. /**
  895. * 执行Model过程中保存的相关信息
  896. *
  897. * @param String $option
  898. * @return Mix
  899. */
  900. final function querySQL($option = '')
  901. {
  902. $allow = array('_queryTimes', '_querySeconds', '_errorInfo', '_exeSQL');
  903. if (in_array($option, $allow)) {
  904. return $this->{$option};
  905. }
  906. return 0;
  907. }
  908. /**
  909. * 将结果编码一下
  910. * @param String $word
  911. * @return String|multitype:
  912. */
  913. public function setQuote($word)//过滤sql字符
  914. {
  915. if (ini_get("magic_quotes_gpc")) {
  916. return $word;
  917. }
  918. return is_array($word) ? array_map('addslashes', $word) : addslashes($word);
  919. }
  920. /**
  921. * 获取错误码
  922. */
  923. public function getCode()
  924. {
  925. return $this->response->getCode();
  926. }
  927. /**
  928. * 获取错误信息
  929. */
  930. public function getMessage()
  931. {
  932. if ($this->response->isError()) {
  933. return $this->response->getMessage();
  934. }
  935. }
  936. /**
  937. * 返回response对象
  938. *
  939. * @return Bool
  940. */
  941. public function getResponse()
  942. {
  943. return $this->response;
  944. }
  945. /**
  946. * 转换字符创
  947. *
  948. * @param $str
  949. * @return array|string
  950. */
  951. public function iconv($str)
  952. {
  953. if (is_array($str)) {
  954. return array_map(function ($n) {
  955. return toUtf8($n);
  956. }, $str);
  957. }
  958. return toUtf8($str);
  959. }
  960. /**
  961. * 如果不存在指定的方法则调用提示错误
  962. *
  963. * @param String $name
  964. * @param Mix $args
  965. * @return Mix
  966. */
  967. public function __call($method, $argvs)
  968. {
  969. if (isset($this->_modelAlias[$method])) {
  970. if (method_exists($this, $this->_modelAlias[$method])) {
  971. return call_user_func_array(array($this, $this->_modelAlias[$method]), $argvs);
  972. }
  973. \Qii::setError(false, __LINE__, 1506, 'Alias ' . get_called_class() . '->' . $method . '()');
  974. }
  975. \Qii::setError(false, __LINE__, 1506, get_called_class() . '->' . $method . '()');
  976. }
  977. }