dao.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  1. <?php
  2. /**
  3. * mysql dao 工具类: 目的是提高写sql语句的效率,但是应该是涉及到sql开发的地方不会太多...
  4. * ver: 2017.05.25 由王刚导入并调试, 慢慢发展, 不着急推广.
  5. * Ps.至于可用性和稳定性还差的远, 直接执行sql语句是最靠谱的方式.
  6. * 用法备注:
  7. * select 用法: 最后必须得有fetch/fetchall/fetchPairs/fetchGroup...
  8. * $dao->select()->from('table') // 必选
  9. * ->where()->eq()/gt()/lt() // 可选
  10. * ->andwhere()->in() // 可选
  11. * ->orderby() // 可选
  12. * ->limit() // 可选
  13. * ->fetch*(); // 必选
  14. * insert 用法: 最后必须得有exec()
  15. * $dao->insert('table') // 必选
  16. * ->data(data) // 必选 data 为['filed'=>value,...]或{'k':v,...}
  17. * ->*check() // 可选
  18. * ->exec() // 必选
  19. * 或 $dao->insert('table')
  20. * ->set('filed')->eq(value)
  21. * ->set()->eq()...
  22. * ->exec()
  23. * update 用法: 必须得有data(),where()和exec()
  24. * $dao->update('table') // 必选
  25. * ->data(change) // 必选 change 为['filed'=>value,...]或{'k':v,...}
  26. * ->*check() // 可选
  27. * ->where()->eq/lt/gt() // 必选
  28. * ->andwhere()->eq/lt/gt() // 可选
  29. * ->exec() // 必选
  30. * 或 * $dao->update('table') // 必选
  31. * ->set('field')->eq(value) // 必选
  32. * ->set()->eq()... // 可选
  33. * ->*check() // 可选
  34. * ->where()->eq/lt/gt() // 必选
  35. * ->andwhere()->eq/lt/gt() // 可选
  36. * ->exec() // 必选
  37. * delete 用法: 必须得有exec
  38. * $dao->delete()->from('table') // 必选
  39. * ->where('field')->eq/lt/gt(value) // 必选
  40. * ->andwhere()->eq/gt/lt()... // 可选
  41. * ->exec() // 必选
  42. * 更多用法继续参考禅道项目中具体代码(本人(gwang)参考的7.0版本).
  43. * (http://dl.cnezsoft.com/zentao/7.0/ZenTaoPMS.7.0.stable.zip)
  44. *
  45. */
  46. /**
  47. * The dao and sql class file of ZenTaoPHP framework.
  48. *
  49. * The author disclaims copyright to this source code. In place of
  50. * a legal notice, here is a blessing:
  51. *
  52. * May you do good and not evil.
  53. * May you find forgiveness for yourself and forgive others.
  54. * May you share freely, never taking more than you give.
  55. */
  56. //use PDO;
  57. /**
  58. * DAO, data access object.
  59. *
  60. * @package framework
  61. */
  62. class dao {
  63. /* Use these strang strings to avoid conflicting with these keywords in the sql body. */
  64. const WHERE = 'wHeRe';
  65. const GROUPBY = 'gRoUp bY';
  66. const HAVING = 'hAvInG';
  67. const ORDERBY = 'oRdEr bY';
  68. const LIMIT = 'lImiT';
  69. /**
  70. * The global dbh(database handler) object.
  71. *
  72. * @var object
  73. * @access protected
  74. */
  75. protected $dbh;
  76. /**
  77. * The global slaveDBH(database handler) object.
  78. * 从数据库, 主从架构, 主库写如, 从库查询
  79. * @var object
  80. * @access protected
  81. */
  82. protected $slaveDBH;
  83. /**
  84. * The sql object, used to creat the query sql.
  85. *
  86. * @var object
  87. * @access protected
  88. */
  89. public $sqlobj;
  90. /**
  91. * The table of current query.
  92. *
  93. * @var string
  94. * @access public
  95. */
  96. public $table;
  97. /**
  98. * The alias of $this->table.
  99. *
  100. * @var string
  101. * @access public
  102. */
  103. public $alias;
  104. /**
  105. * The fields will be returned.
  106. *
  107. * @var string
  108. * @access public
  109. */
  110. public $fields;
  111. /**
  112. * The query mode, raw or magic.
  113. *
  114. * This var is used to diff dao::from() with sql::from().
  115. *
  116. * @var string
  117. * @access public
  118. */
  119. public $mode;
  120. /**
  121. * The query method: insert, select, update, delete, replace.
  122. *
  123. * @var string
  124. * @access public
  125. */
  126. public $method;
  127. /**
  128. * The sql code of need repair table.
  129. *
  130. * @var string
  131. * @access public
  132. */
  133. public $repairCode = '|1034|1035|1194|1195|1459|';
  134. /**
  135. * The queries executed. Every query will be saved in this array.
  136. *
  137. * @var array
  138. * @access public
  139. */
  140. static public $querys = array();
  141. /**
  142. * The errors.
  143. *
  144. * @var array
  145. * @access public
  146. */
  147. static public $errors = array();
  148. /**
  149. * The construct method.
  150. *
  151. * @access public
  152. * @return void
  153. */
  154. public function __construct() {
  155. }
  156. /**
  157. * Connect to database.
  158. * @param assoc_array $config 配置
  159. * @access public
  160. * @return void
  161. */
  162. public function connectDB($config) {
  163. global $dbh, $slaveDBH;
  164. if (isset($config->paydb->host)) {
  165. $this->dbh = $dbh = $this->connectByPDO($config->paydb);
  166. }
  167. if (isset($config->slaveDB->host)) {
  168. $this->slaveDBH = $slaveDBH = $this->connectByPDO($config->slaveDB);
  169. }
  170. }
  171. /**
  172. * Connect database by PDO.
  173. *
  174. * @param object $params the database params.
  175. * @access private
  176. * @return object|bool
  177. */
  178. private function connectByPDO($params) {
  179. if (!isset($params->driver))
  180. self::triggerError('no pdo driver defined, it should be mysql or sqlite', __FILE__, __LINE__, $exit = true);
  181. if (!isset($params->user))
  182. return false;
  183. if ($params->driver == 'mysql') {
  184. $dsn = "mysql:host={$params->host}; port={$params->port}; dbname={$params->name}";
  185. }
  186. try {
  187. $dbh = new \PDO($dsn, $params->user, $params->password, array(PDO::ATTR_PERSISTENT => $params->persistant));
  188. $dbh->exec("SET NAMES {$params->encoding}");
  189. /* If run on linux, set emulatePrepare and bufferQuery to true. */
  190. if (!isset($params->emulatePrepare) and PHP_OS == 'Linux')
  191. $params->emulatePrepare = true;
  192. if (!isset($params->bufferQuery) and PHP_OS == 'Linux')
  193. $params->bufferQuery = true;
  194. $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
  195. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  196. if (isset($params->strictMode) and $params->strictMode == false)
  197. $dbh->exec("SET @@sql_mode= ''");
  198. if (isset($params->emulatePrepare))
  199. $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, $params->emulatePrepare);
  200. if (isset($params->bufferQuery))
  201. $dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, $params->bufferQuery);
  202. return $dbh;
  203. } catch (PDOException $exception) {
  204. self::triggerError($exception->getMessage(), __FILE__, __LINE__, $exit = true);
  205. }
  206. }
  207. /**
  208. * Set the $table property.
  209. *
  210. * @param string $table
  211. * @access private
  212. * @return void
  213. */
  214. private function setTable($table) {
  215. $this->table = $table;
  216. }
  217. /**
  218. * Set the $alias property.
  219. *
  220. * @param string $alias
  221. * @access private
  222. * @return void
  223. */
  224. private function setAlias($alias) {
  225. $this->alias = $alias;
  226. }
  227. /**
  228. * Set the $fields property.
  229. *
  230. * @param string $fields
  231. * @access private
  232. * @return void
  233. */
  234. private function setFields($fields) {
  235. $this->fields = $fields;
  236. }
  237. /**
  238. * Reset the vars.
  239. *
  240. * @access private
  241. * @return void
  242. */
  243. private function reset() {
  244. $this->setFields('');
  245. $this->setTable('');
  246. $this->setAlias('');
  247. $this->setMode('');
  248. $this->setMethod('');
  249. }
  250. //-------------------- According to the query method, call according method of sql class. --------------------//
  251. /**
  252. * Set the query mode. If the method if like findByxxx, the mode is magic. Else, the mode is raw.
  253. *
  254. * @param string $mode magic|raw
  255. * @access private
  256. * @return void
  257. */
  258. private function setMode($mode = '') {
  259. $this->mode = $mode;
  260. }
  261. /**
  262. * Set the query method: select|update|insert|delete|replace
  263. *
  264. * @param string $method
  265. * @access private
  266. * @return void
  267. */
  268. private function setMethod($method = '') {
  269. $this->method = $method;
  270. }
  271. /**
  272. * The select method, call sql::select().
  273. *
  274. * @param string $fields
  275. * @access public
  276. * @return object the dao object self.
  277. */
  278. public function select($fields = '*') {
  279. $this->setMode('raw');
  280. $this->setMethod('select');
  281. $this->sqlobj = sql::select($fields);
  282. return $this;
  283. }
  284. /**
  285. * The count method, call sql::select() and from().
  286. * use as $this->dao->select()->from(TABLE_BUG)->where()->count();
  287. *
  288. * @access public
  289. * @return void
  290. */
  291. public function count() {
  292. /* Get the SELECT, FROM position, thus get the fields, replace it by count(*). */
  293. // $this->fields
  294. $sql = $this->processSQL();
  295. $sql = str_replace('SELECT', 'SELECT SQL_CALC_FOUND_ROWS ', $sql);
  296. /* Remove the part after order and limit. */
  297. $subLength = strlen($sql);
  298. $orderPOS = strripos($sql, DAO::ORDERBY);
  299. $limitPOS = strripos($sql, DAO::LIMIT);
  300. if ($limitPOS)
  301. $subLength = $limitPOS;
  302. if ($orderPOS)
  303. $subLength = $orderPOS;
  304. $sql = substr($sql, 0, $subLength);
  305. self::$querys[] = $sql;
  306. // var_dump($sql);
  307. /* Get the records count. */
  308. try {
  309. $row = $this->dbh->query($sql)->fetch(PDO::FETCH_OBJ);
  310. } catch (PDOException $e) {
  311. $this->sqlError($e);
  312. }
  313. // CLogUtil_HP::paylog($sql);
  314. // var_dump($row);
  315. $sql = 'SELECT FOUND_ROWS() as recTotal;';
  316. $row = $this->dbh->query($sql)->fetch();
  317. return $row->recTotal;
  318. }
  319. /**
  320. * The select method, call sql::update().
  321. *
  322. * @param string $table
  323. * @access public
  324. * @return object the dao object self.
  325. */
  326. public function update($table) {
  327. $this->setMode('raw');
  328. $this->setMethod('update');
  329. $this->sqlobj = sql::update($table);
  330. $this->setTable($table);
  331. return $this;
  332. }
  333. /**
  334. * The delete method, call sql::delete().
  335. *
  336. * @access public
  337. * @return object the dao object self.
  338. */
  339. public function delete() {
  340. $this->setMode('raw');
  341. $this->setMethod('delete');
  342. $this->sqlobj = sql::delete();
  343. return $this;
  344. }
  345. /**
  346. * The insert method, call sql::insert().
  347. *
  348. * @param string $table
  349. * @access public
  350. * @return object the dao object self.
  351. */
  352. public function insert($table) {
  353. $this->setMode('raw');
  354. $this->setMethod('insert');
  355. $this->sqlobj = sql::insert($table);
  356. $this->setTable($table);
  357. return $this;
  358. }
  359. /**
  360. * The replace method, call sql::replace().
  361. *
  362. * @param string $table
  363. * @access public
  364. * @return object the dao object self.
  365. */
  366. public function replace($table) {
  367. $this->setMode('raw');
  368. $this->setMethod('replace');
  369. $this->sqlobj = sql::replace($table);
  370. $this->setTable($table);
  371. return $this;
  372. }
  373. /**
  374. * Set the from table.
  375. *
  376. * @param string $table
  377. * @access public
  378. * @return object the dao object self.
  379. */
  380. public function from($table) {
  381. $this->setTable($table);
  382. if ($this->mode == 'raw')
  383. $this->sqlobj->from($table);
  384. return $this;
  385. }
  386. /**
  387. * Set the fields.
  388. *
  389. * @param string $fields
  390. * @access public
  391. * @return object the dao object self.
  392. */
  393. public function fields($fields) {
  394. $this->setFields($fields);
  395. return $this;
  396. }
  397. /**
  398. * Alias a table, equal the AS keyword. (Don't use AS, because it's a php keyword.)
  399. *
  400. * @param string $alias
  401. * @access public
  402. * @return object the dao object self.
  403. */
  404. public function alias($alias) {
  405. if (empty($this->alias))
  406. $this->setAlias($alias);
  407. $this->sqlobj->alias($alias);
  408. return $this;
  409. }
  410. /**
  411. * Set the data to update or insert.
  412. *
  413. * @param object $data the data object or array
  414. * @access public
  415. * @return object the dao object self.
  416. */
  417. public function data($data) {
  418. if (!is_object($data))
  419. $data = (object) $data;
  420. $this->sqlobj->data($data);
  421. return $this;
  422. }
  423. //-------------------- The sql related method. --------------------//
  424. /**
  425. * Get the sql string.
  426. *
  427. * @access public
  428. * @return string the sql string after process.
  429. */
  430. public function get() {
  431. return $this->processKeywords($this->processSQL());
  432. }
  433. /**
  434. * Print the sql string.
  435. *
  436. * @access public
  437. * @return void
  438. */
  439. public function printSQL() {
  440. echo $this->processSQL();
  441. }
  442. /**
  443. * Process the sql, replace the table, fields.
  444. *
  445. * @access private
  446. * @return string the sql string after process.
  447. */
  448. private function processSQL() {
  449. $sql = $this->sqlobj->get();
  450. /* If the mode is magic, process the $fields and $table. */
  451. if ($this->mode == 'magic') {
  452. if ($this->fields == '')
  453. $this->fields = '*';
  454. if ($this->table == '')
  455. $this->triggerError('Must set the table name', __FILE__, __LINE__, $exit = true);
  456. $sql = sprintf($this->sqlobj->get(), $this->fields, $this->table);
  457. }
  458. self::$querys[] = $this->processKeywords($sql);
  459. return $sql;
  460. }
  461. /**
  462. * Trriger an error.
  463. *
  464. * @param string $message error message
  465. * @param string $file the file error occers
  466. * @param int $line the line error occers
  467. * @param bool $exit exit the program or not
  468. * @access public
  469. * @return void
  470. */
  471. private function triggerError($message, $file, $line, $exit = false) {
  472. /* Set the error info. */
  473. $log = "ERROR: " . CommUtil::str2UTF8($message) . " in "
  474. . CommUtil::str2UTF8($file) . " on line $line";
  475. if (isset($_SERVER['SCRIPT_URI']))
  476. $log .= ", request: $_SERVER[SCRIPT_URI]";
  477. ;
  478. $trace = debug_backtrace();
  479. extract($trace[0]); # function
  480. extract($trace[1]); # line
  481. $log .= ", last called by $file on line $line through function $function.\n";
  482. // CLog::err($log, "dao");
  483. // CLog::err($trace, "dao");
  484. /* Trigger it. */
  485. trigger_error($log, $exit ? E_USER_ERROR : E_USER_WARNING);
  486. }
  487. /**
  488. * Process the sql keywords, replace the constants to normal.
  489. *
  490. * @param string $sql
  491. * @access private
  492. * @return string the sql string.
  493. */
  494. private function processKeywords($sql) {
  495. return str_replace(array(DAO::WHERE, DAO::GROUPBY, DAO::HAVING, DAO::ORDERBY, DAO::LIMIT), array('WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT'), $sql);
  496. }
  497. //-------------------- Query related methods. --------------------//
  498. /**
  499. * Set the dbh.
  500. *
  501. * You can use like this: $this->dao->dbh($dbh), thus you can handle two database.
  502. *
  503. * @param object $dbh
  504. * @access public
  505. * @return object the dao object self.
  506. */
  507. public function dbh($dbh) {
  508. $this->dbh = $dbh;
  509. return $this;
  510. }
  511. /**
  512. * Query the sql, return the statement object.
  513. *
  514. * @param string $sql
  515. * @access public
  516. * @return object the PDOStatement object.
  517. */
  518. public function query($sql = '') {
  519. if (!empty(dao::$errors))
  520. return new PDOStatement(); // If any error, return an empty statement object to make sure the remain method to execute.
  521. if ($sql) {
  522. if (is_null($this->sqlobj)) {
  523. $this->sqlobj = sql::factory();
  524. }
  525. $this->sqlobj->sql = $sql;
  526. }
  527. $sql = $this->processSQL();
  528. try {
  529. $method = $this->method;
  530. $this->reset();
  531. // var_dump($sql);
  532. if ($this->slaveDBH and $method == 'select') {
  533. return $this->slaveDBH->query($sql);
  534. } else {
  535. return $this->dbh->query($sql);
  536. }
  537. } catch (PDOException $e) {
  538. $this->sqlError($e);
  539. }
  540. }
  541. /**
  542. * Page the records, set the limit part auto.
  543. *
  544. * @param object $pager
  545. * @access public
  546. * @return object the dao object self.
  547. */
  548. public function page($pager) {
  549. if (!is_object($pager))
  550. return $this;
  551. /* If the record total is 0, compute it. */
  552. if ($pager->recTotal == 0) {
  553. /* Get the SELECT, FROM position, thus get the fields, replace it by count(*). */
  554. $sql = $this->get();
  555. $selectPOS = strpos($sql, 'SELECT') + strlen('SELECT');
  556. $fromPOS = strpos($sql, 'FROM');
  557. $fields = substr($sql, $selectPOS, $fromPOS - $selectPOS);
  558. $sql = str_replace($fields, ' COUNT(*) AS recTotal ', $sql);
  559. /* Remove the part after order and limit. */
  560. $subLength = strlen($sql);
  561. $orderPOS = strripos($sql, 'order ');
  562. $limitPOS = strripos($sql, 'limit');
  563. if ($limitPOS)
  564. $subLength = $limitPOS;
  565. if ($orderPOS)
  566. $subLength = $orderPOS;
  567. $sql = substr($sql, 0, $subLength);
  568. self::$querys[] = $sql;
  569. /* Get the records count. */
  570. try {
  571. $row = $this->dbh->query($sql)->fetch(PDO::FETCH_OBJ);
  572. } catch (PDOException $e) {
  573. $this->sqlError($e);
  574. }
  575. $pager->setRecTotal($row->recTotal);
  576. $pager->setPageTotal();
  577. }
  578. $this->sqlobj->limit($pager->limit());
  579. return $this;
  580. }
  581. /**
  582. * Execute the sql. It's different with query(), which return the stmt object. But this not.
  583. *
  584. * @param string $sql
  585. * @access public
  586. * @return int the modified or deleted records.
  587. */
  588. public function exec($sql = '') {
  589. if (!empty(dao::$errors))
  590. return new PDOStatement(); // If any error, return an empty statement object to make sure the remain method to execute.
  591. if ($sql) {
  592. if (is_null($this->sqlobj)) {
  593. $this->sqlobj = sql::factory();
  594. }
  595. $this->sqlobj->sql = $sql;
  596. }
  597. $sql = $this->processSQL();
  598. // var_dump($sql);
  599. try {
  600. $this->reset();
  601. return $this->dbh->exec($sql);
  602. } catch (PDOException $e) {
  603. $this->sqlError($e);
  604. }
  605. }
  606. //-------------------- Fetch related methods. -------------------//
  607. /**
  608. * Fetch one record.
  609. *
  610. * @param string $field if the field is set, only return the value of this field, else return this record
  611. * @access public
  612. * @return object|mixed
  613. */
  614. public function fetch($field = '') {
  615. if (empty($field))
  616. return $this->query()->fetch();
  617. $this->setFields($field);
  618. $result = $this->query()->fetch(PDO::FETCH_OBJ);
  619. if ($result)
  620. return $result->$field;
  621. }
  622. /**
  623. * Fetch all records.
  624. *
  625. * @param string $keyField the key field, thus the return records is keyed by this field
  626. * @access public
  627. * @return array the records
  628. */
  629. public function fetchAll($keyField = '') {
  630. $stmt = $this->query();
  631. if (empty($keyField))
  632. return $stmt->fetchAll();
  633. $rows = array();
  634. while ($row = $stmt->fetch())
  635. $rows[$row->$keyField] = $row;
  636. return $rows;
  637. }
  638. /**
  639. * Fetch all records and group them by one field.
  640. *
  641. * @param string $groupField the field to group by
  642. * @param string $keyField the field of key
  643. * @access public
  644. * @return array the records.
  645. */
  646. public function fetchGroup($groupField, $keyField = '') {
  647. $stmt = $this->query();
  648. $rows = array();
  649. while ($row = $stmt->fetch()) {
  650. empty($keyField) ? $rows[$row->$groupField][] = $row : $rows[$row->$groupField][$row->$keyField] = $row;
  651. }
  652. return $rows;
  653. }
  654. /**
  655. * Fetch array like key=>value.
  656. *
  657. * If the keyFiled and valueField not set, use the first and last in the record.
  658. *
  659. * @param string $keyField
  660. * @param string $valueField
  661. * @access public
  662. * @return array
  663. */
  664. public function fetchPairs($keyField = '', $valueField = '') {
  665. $pairs = array();
  666. $ready = false;
  667. $stmt = $this->query();
  668. while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  669. if (!$ready) {
  670. if (empty($keyField))
  671. $keyField = key($row);
  672. if (empty($valueField)) {
  673. end($row);
  674. $valueField = key($row);
  675. }
  676. $ready = true;
  677. }
  678. $pairs[$row[$keyField]] = $row[$valueField];
  679. }
  680. return $pairs;
  681. }
  682. /**
  683. * Return the last insert ID.
  684. *
  685. * @access public
  686. * @return int
  687. */
  688. public function lastInsertID() {
  689. return $this->dbh->lastInsertID();
  690. }
  691. //-------------------- Magic methods.--------------------//
  692. /**
  693. * Use it to do some convenient queries.
  694. *
  695. * @param string $funcName the function name to be called
  696. * @param array $funcArgs the params
  697. * @access public
  698. * @return object the dao object self.
  699. */
  700. public function __call($funcName, $funcArgs) {
  701. $funcName = strtolower($funcName);
  702. /* findByxxx, xxx as will be in the where. */
  703. if (strpos($funcName, 'findby') !== false) {
  704. $this->setMode('magic');
  705. $field = str_replace('findby', '', $funcName);
  706. if (count($funcArgs) == 1) {
  707. $operator = '=';
  708. $value = $funcArgs[0];
  709. } else {
  710. $operator = $funcArgs[0];
  711. $value = $funcArgs[1];
  712. }
  713. $this->sqlobj = sql::select('%s')->from('%s')->where($field, $operator, $value);
  714. return $this;
  715. }
  716. /* Fetch10. */ elseif (strpos($funcName, 'fetch') !== false) {
  717. $max = str_replace('fetch', '', $funcName);
  718. $stmt = $this->query();
  719. $rows = array();
  720. $key = isset($funcArgs[0]) ? $funcArgs[0] : '';
  721. $i = 0;
  722. while ($row = $stmt->fetch()) {
  723. $key ? $rows[$row->$key] = $row : $rows[] = $row;
  724. $i++;
  725. if ($i == $max)
  726. break;
  727. }
  728. return $rows;
  729. }
  730. /* Others, call the method in sql class. */ else {
  731. /* Create the max counts of sql class methods, and then create $arg0, $arg1... */
  732. for ($i = 0; $i < SQL::MAX_ARGS; $i++) {
  733. ${"arg$i"} = isset($funcArgs[$i]) ? $funcArgs[$i] : null;
  734. }
  735. $this->sqlobj->$funcName($arg0, $arg1, $arg2);
  736. return $this;
  737. }
  738. }
  739. //-------------------- Checking.--------------------//
  740. /**
  741. * Check a filed is satisfied with the check rule.
  742. *
  743. * @param string $fieldName the field to check
  744. * @param string $funcName the check rule
  745. * @access public
  746. * @return object the dao object self.
  747. */
  748. public function check($fieldName, $funcName) {
  749. /* If no this field in the data, reuturn. */
  750. if (!isset($this->sqlobj->data->$fieldName))
  751. return $this;
  752. /* Set the field label and value. */
  753. global $lang, $config, $app;
  754. $table = strtolower(str_replace(array($config->db->prefix, '`'), '', $this->table));
  755. $fieldLabel = isset($lang->$table->$fieldName) ? $lang->$table->$fieldName : $fieldName;
  756. $value = $this->sqlobj->data->$fieldName;
  757. /* Check unique. */
  758. if ($funcName == 'unique') {
  759. $args = func_get_args();
  760. $sql = "SELECT COUNT(*) AS count FROM $this->table WHERE `$fieldName` = " . $this->sqlobj->quote($value);
  761. if (isset($args[2]))
  762. $sql .= ' AND ' . $args[2];
  763. try {
  764. $row = $this->dbh->query($sql)->fetch();
  765. if ($row->count != 0)
  766. $this->logError($funcName, $fieldName, $fieldLabel, array($value));
  767. } catch (PDOException $e) {
  768. $this->sqlError($e);
  769. }
  770. } else {
  771. /* Create the params. */
  772. $funcArgs = func_get_args();
  773. unset($funcArgs[0]);
  774. unset($funcArgs[1]);
  775. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  776. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  777. }
  778. $checkFunc = 'check' . $funcName;
  779. if (validater::$checkFunc($value, $arg0, $arg1, $arg2) === false) {
  780. $this->logError($funcName, $fieldName, $fieldLabel, $funcArgs);
  781. }
  782. }
  783. return $this;
  784. }
  785. /**
  786. * Check a field, if satisfied with the condition.
  787. *
  788. * @param string $condition
  789. * @param string $fieldName
  790. * @param string $funcName
  791. * @access public
  792. * @return object the dao object self.
  793. */
  794. public function checkIF($condition, $fieldName, $funcName) {
  795. if (!$condition)
  796. return $this;
  797. $funcArgs = func_get_args();
  798. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  799. ${"arg$i"} = isset($funcArgs[$i + 3]) ? $funcArgs[$i + 3] : null;
  800. }
  801. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  802. return $this;
  803. }
  804. /**
  805. * Batch check some fileds.
  806. *
  807. * @param string $fields the fields to check, join with ,
  808. * @param string $funcName
  809. * @access public
  810. * @return object the dao object self.
  811. */
  812. public function batchCheck($fields, $funcName) {
  813. $fields = explode(',', str_replace(' ', '', $fields));
  814. $funcArgs = func_get_args();
  815. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  816. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  817. }
  818. foreach ($fields as $fieldName)
  819. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  820. return $this;
  821. }
  822. /**
  823. * Batch check fields on the condition is true.
  824. *
  825. * @param string $condition
  826. * @param string $fields
  827. * @param string $funcName
  828. * @access public
  829. * @return object the dao object self.
  830. */
  831. public function batchCheckIF($condition, $fields, $funcName) {
  832. if (!$condition)
  833. return $this;
  834. $fields = explode(',', str_replace(' ', '', $fields));
  835. $funcArgs = func_get_args();
  836. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  837. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  838. }
  839. foreach ($fields as $fieldName)
  840. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  841. return $this;
  842. }
  843. /**
  844. * Check the fields according the the database schema.
  845. *
  846. * @param string $skipFields fields to skip checking
  847. * @access public
  848. * @return object the dao object self.
  849. */
  850. public function autoCheck($skipFields = '') {
  851. $fields = $this->getFieldsType();
  852. $skipFields = ",$skipFields,";
  853. foreach ($fields as $fieldName => $validater) {
  854. if (strpos($skipFields, $fieldName) !== false)
  855. continue; // skip it.
  856. if (!isset($this->sqlobj->data->$fieldName))
  857. continue;
  858. if ($validater['rule'] == 'skip')
  859. continue;
  860. $options = array();
  861. if (isset($validater['options']))
  862. $options = array_values($validater['options']);
  863. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  864. ${"arg$i"} = isset($options[$i]) ? $options[$i] : null;
  865. }
  866. $this->check($fieldName, $validater['rule'], $arg0, $arg1, $arg2);
  867. }
  868. return $this;
  869. }
  870. /**
  871. * 检查表是否存在
  872. * @param type $tableName
  873. * @return type
  874. */
  875. public function tableExist($tableName) {
  876. $this->reset();
  877. $this->setMethod('select');
  878. $sql = "SELECT 1 FROM $tableName LIMIT 1";
  879. try {
  880. if ($this->slaveDBH and $this->method == 'select') {
  881. $ret = $this->slaveDBH->query($sql)->fetch();
  882. } else {
  883. $ret = $this->dbh->query($sql)->fetch();
  884. }
  885. } catch (Exception $exc) {
  886. return false;
  887. }
  888. // Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
  889. return $ret !== FALSE; # false代表表不存在
  890. }
  891. /**
  892. * Log the error.
  893. *
  894. * For the error notice, see module/common/lang.
  895. *
  896. * @param string $checkType the check rule
  897. * @param string $fieldName the field name
  898. * @param string $fieldLabel the field label
  899. * @param array $funcArgs the args
  900. * @access public
  901. * @return void
  902. */
  903. public function logError($checkType, $fieldName, $fieldLabel, $funcArgs = array()) {
  904. global $lang;
  905. $error = $lang->error->$checkType;
  906. $replaces = array_merge(array($fieldLabel), $funcArgs); // the replace values.
  907. /* Just a string, cycle the $replaces. */
  908. if (!is_array($error)) {
  909. foreach ($replaces as $replace) {
  910. $pos = strpos($error, '%s');
  911. if ($pos === false)
  912. break;
  913. $error = substr($error, 0, $pos) . $replace . substr($error, $pos + 2);
  914. }
  915. }
  916. /* If the error define is an array, select the one which %s counts match the $replaces. */ else {
  917. /* Remove the empty items. */
  918. foreach ($replaces as $key => $value)
  919. if (is_null($value))
  920. unset($replaces[$key]);
  921. $replacesCount = count($replaces);
  922. foreach ($error as $errorString) {
  923. if (substr_count($errorString, '%s') == $replacesCount) {
  924. $error = vsprintf($errorString, $replaces);
  925. }
  926. }
  927. }
  928. dao::$errors[$fieldName][] = $error;
  929. }
  930. /**
  931. * Judge any error or not.
  932. *
  933. * @access public
  934. * @return bool
  935. */
  936. public static function isError() {
  937. return !empty(dao::$errors);
  938. }
  939. /**
  940. * Get the errors.
  941. *
  942. * @param boolean $join
  943. * @access public
  944. * @return array
  945. */
  946. public static function getError($join = false) {
  947. $errors = dao::$errors;
  948. dao::$errors = array(); // Must clear it.
  949. if (!$join)
  950. return $errors;
  951. if (is_array($errors)) {
  952. $message = '';
  953. foreach ($errors as $item) {
  954. is_array($item) ? $message .= join('\n', $item) . '\n' : $message .= $item . '\n';
  955. }
  956. return $message;
  957. }
  958. }
  959. /**
  960. * Get the defination of fields of the table.
  961. *
  962. * @access private
  963. * @return array
  964. */
  965. private function getFieldsType() {
  966. try {
  967. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
  968. $sql = "DESC $this->table";
  969. $rawFields = $this->dbh->query($sql)->fetchAll();
  970. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  971. } catch (PDOException $e) {
  972. $this->sqlError($e);
  973. }
  974. foreach ($rawFields as $rawField) {
  975. $firstPOS = strpos($rawField->type, '(');
  976. $type = substr($rawField->type, 0, $firstPOS > 0 ? $firstPOS : strlen($rawField->type));
  977. $type = str_replace(array('big', 'small', 'medium', 'tiny', 'var'), '', $type);
  978. $field = array();
  979. if ($type == 'enum' or $type == 'set') {
  980. $rangeBegin = $firstPOS + 2; // Remove the first quote.
  981. $rangeEnd = strrpos($rawField->type, ')') - 1; // Remove the last quote.
  982. $range = substr($rawField->type, $rangeBegin, $rangeEnd - $rangeBegin);
  983. $field['rule'] = 'reg';
  984. $field['options']['reg'] = '/' . str_replace("','", '|', $range) . '/';
  985. } elseif ($type == 'char') {
  986. $begin = $firstPOS + 1;
  987. $end = strpos($rawField->type, ')', $begin);
  988. $length = substr($rawField->type, $begin, $end - $begin);
  989. $field['rule'] = 'length';
  990. $field['options']['max'] = $length;
  991. $field['options']['min'] = 0;
  992. } elseif ($type == 'int') {
  993. $field['rule'] = 'int';
  994. } elseif ($type == 'float' or $type == 'double') {
  995. $field['rule'] = 'float';
  996. } elseif ($type == 'date') {
  997. $field['rule'] = 'date';
  998. } else {
  999. $field['rule'] = 'skip';
  1000. }
  1001. $fields[$rawField->field] = $field;
  1002. }
  1003. return $fields;
  1004. }
  1005. /**
  1006. * Process SQL error by code.
  1007. *
  1008. * @param object $exception
  1009. * @access public
  1010. * @return void
  1011. */
  1012. public function sqlError($exception) {
  1013. $errorInfo = $exception->errorInfo;
  1014. $errorCode = $errorInfo[1];
  1015. $errorMsg = $errorInfo[2];
  1016. $message = $exception->getMessage();
  1017. if (strpos($this->repairCode, "|$errorCode|") !== false #
  1018. or ( $errorCode == '1016' and strpos($errorMsg, 'errno: 145') !== false)) {
  1019. $message .= ' repairTable';
  1020. }
  1021. $sql = $this->sqlobj->get();
  1022. $this->triggerError($message . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
  1023. }
  1024. }
  1025. /**
  1026. * The SQL class.
  1027. *
  1028. * @package framework
  1029. */
  1030. class sql {
  1031. /**
  1032. * The max count of params of all methods.
  1033. *
  1034. */
  1035. const MAX_ARGS = 3;
  1036. /**
  1037. * The sql string.
  1038. *
  1039. * @var string
  1040. * @access public
  1041. */
  1042. public $sql = '';
  1043. /**
  1044. * The global $dbh.
  1045. *
  1046. *
  1047. * @access protected
  1048. */
  1049. protected $dbh;
  1050. /**
  1051. * The data to update or insert.
  1052. *
  1053. * @var mix
  1054. * @access protected
  1055. */
  1056. public $data;
  1057. /**
  1058. * Is the first time to call set.
  1059. *
  1060. * @var bool
  1061. * @access private;
  1062. */
  1063. private $isFirstSet = true;
  1064. /**
  1065. * If in the logic of judge condition or not.
  1066. *
  1067. * @var bool
  1068. * @access private;
  1069. */
  1070. private $inCondition = false;
  1071. /**
  1072. * The condition is true or not.
  1073. *
  1074. * @var bool
  1075. * @access private;
  1076. */
  1077. private $conditionIsTrue = false;
  1078. /**
  1079. * Magic quote or not.
  1080. *
  1081. * @var bool
  1082. * @access public
  1083. */
  1084. public $magicQuote;
  1085. /**
  1086. * The construct function. user factory() to instance it.
  1087. *
  1088. * @param string $table
  1089. * @access private
  1090. * @return void
  1091. */
  1092. private function __construct($table = '') {
  1093. global $dbh;
  1094. $this->dbh = $dbh;
  1095. $this->magicQuote = false; // get_magic_quotes_gpc();
  1096. }
  1097. /**
  1098. * The factory method.
  1099. *
  1100. * @param string $table
  1101. * @access public
  1102. * @return object the sql object.
  1103. */
  1104. public static function factory($table = '') {
  1105. return new sql($table);
  1106. }
  1107. /**
  1108. * The sql is select.
  1109. *
  1110. * @param string $field
  1111. * @access public
  1112. * @return object the sql object.
  1113. */
  1114. public static function select($field = '*') {
  1115. $sqlobj = self::factory();
  1116. $sqlobj->sql = "SELECT $field ";
  1117. return $sqlobj;
  1118. }
  1119. /**
  1120. * The sql is update.
  1121. *
  1122. * @param string $table
  1123. * @access public
  1124. * @return object the sql object.
  1125. */
  1126. public static function update($table) {
  1127. $sqlobj = self::factory();
  1128. $sqlobj->sql = "UPDATE $table SET ";
  1129. return $sqlobj;
  1130. }
  1131. /**
  1132. * The sql is insert.
  1133. *
  1134. * @param string $table
  1135. * @access public
  1136. * @return object the sql object.
  1137. */
  1138. public static function insert($table) {
  1139. $sqlobj = self::factory();
  1140. $sqlobj->sql = "INSERT INTO $table SET ";
  1141. return $sqlobj;
  1142. }
  1143. /**
  1144. * The sql is replace.
  1145. *
  1146. * @param string $table
  1147. * @access public
  1148. * @return object the sql object.
  1149. */
  1150. public static function replace($table) {
  1151. $sqlobj = self::factory();
  1152. $sqlobj->sql = "REPLACE $table SET ";
  1153. return $sqlobj;
  1154. }
  1155. /**
  1156. * The sql is delete.
  1157. *
  1158. * @access public
  1159. * @return object the sql object.
  1160. */
  1161. public static function delete() {
  1162. $sqlobj = self::factory();
  1163. $sqlobj->sql = "DELETE ";
  1164. return $sqlobj;
  1165. }
  1166. /**
  1167. * Join the data items by key = value.
  1168. *
  1169. * @param object $data
  1170. * @access public
  1171. * @return object the sql object.
  1172. */
  1173. public function data($data) {
  1174. $data = (object) $data;
  1175. foreach ($data as $field => $value) {
  1176. if (!preg_match('|^\w+$|', $field)) {
  1177. unset($data->$field);
  1178. continue;
  1179. }
  1180. $this->sql .= "`$field` = " . $this->quote($value) . ',';
  1181. }
  1182. $this->data = $data;
  1183. $this->sql = rtrim($this->sql, ','); // Remove the last ','.
  1184. return $this;
  1185. }
  1186. /**
  1187. * Aadd an '(' at left.
  1188. *
  1189. * @param int $count
  1190. * @access public
  1191. * @return ojbect the sql object.
  1192. */
  1193. public function markLeft($count = 1) {
  1194. $this->sql .= str_repeat('(', $count);
  1195. return $this;
  1196. }
  1197. /**
  1198. * Add an ')' ad right.
  1199. *
  1200. * @param int $count
  1201. * @access public
  1202. * @return object the sql object.
  1203. */
  1204. public function markRight($count = 1) {
  1205. $this->sql .= str_repeat(')', $count);
  1206. return $this;
  1207. }
  1208. /**
  1209. * The set part.
  1210. *
  1211. * @param string $set
  1212. * @access public
  1213. * @return object the sql object.
  1214. */
  1215. public function set($set) {
  1216. if ($this->isFirstSet) {
  1217. $this->sql .= " $set ";
  1218. $this->isFirstSet = false;
  1219. } else {
  1220. $this->sql .= ", $set";
  1221. }
  1222. return $this;
  1223. }
  1224. /**
  1225. * Create the from part.
  1226. *
  1227. * @param string $table
  1228. * @access public
  1229. * @return object the sql object.
  1230. */
  1231. public function from($table) {
  1232. $this->sql .= "FROM $table";
  1233. return $this;
  1234. }
  1235. /**
  1236. * Create the Alias part.
  1237. *
  1238. * @param string $alias
  1239. * @access public
  1240. * @return object the sql object.
  1241. */
  1242. public function alias($alias) {
  1243. $this->sql .= " AS $alias ";
  1244. return $this;
  1245. }
  1246. /**
  1247. * Create the left join part.
  1248. *
  1249. * @param string $table
  1250. * @access public
  1251. * @return object the sql object.
  1252. */
  1253. public function leftJoin($table) {
  1254. $this->sql .= " LEFT JOIN $table";
  1255. return $this;
  1256. }
  1257. /**
  1258. * Create the on part.
  1259. *
  1260. * @param string $condition
  1261. * @access public
  1262. * @return object the sql object.
  1263. */
  1264. public function on($condition) {
  1265. $this->sql .= " ON $condition ";
  1266. return $this;
  1267. }
  1268. /**
  1269. * Begin condition judge.
  1270. *
  1271. * @param bool $condition
  1272. * @access public
  1273. * @return object the sql object.
  1274. */
  1275. public function beginIF($condition) {
  1276. $this->inCondition = true;
  1277. $this->conditionIsTrue = $condition;
  1278. return $this;
  1279. }
  1280. /**
  1281. * End the condition judge.
  1282. *
  1283. * @access public
  1284. * @return object the sql object.
  1285. */
  1286. public function fi() {
  1287. $this->inCondition = false;
  1288. $this->conditionIsTrue = false;
  1289. return $this;
  1290. }
  1291. /**
  1292. * Create the where part.
  1293. *
  1294. * @param string $arg1 the field name
  1295. * @param string $arg2 the operator
  1296. * @param string $arg3 the value
  1297. * @access public
  1298. * @return object the sql object.
  1299. */
  1300. public function where($arg1, $arg2 = null, $arg3 = null) {
  1301. if ($this->inCondition and!$this->conditionIsTrue)
  1302. return $this;
  1303. if ($arg3 !== null) {
  1304. $value = $this->quote($arg3);
  1305. $condition = "`$arg1` $arg2 " . $this->quote($arg3);
  1306. } else {
  1307. $condition = $arg1;
  1308. }
  1309. $this->sql .= ' ' . DAO::WHERE . " $condition ";
  1310. return $this;
  1311. }
  1312. /**
  1313. * Create the AND part.
  1314. *
  1315. * @param string $condition
  1316. * @access public
  1317. * @return object the sql object.
  1318. */
  1319. public function andWhere($condition) {
  1320. if ($this->inCondition and!$this->conditionIsTrue)
  1321. return $this;
  1322. $this->sql .= " AND $condition ";
  1323. return $this;
  1324. }
  1325. /**
  1326. * Create the OR part.
  1327. *
  1328. * @param bool $condition
  1329. * @access public
  1330. * @return object the sql object.
  1331. */
  1332. public function orWhere($condition) {
  1333. if ($this->inCondition and!$this->conditionIsTrue)
  1334. return $this;
  1335. $this->sql .= " OR $condition ";
  1336. return $this;
  1337. }
  1338. /**
  1339. * Create the '='.
  1340. *
  1341. * @param string $value
  1342. * @access public
  1343. * @return object the sql object.
  1344. */
  1345. public function eq($value) {
  1346. if ($this->inCondition and!$this->conditionIsTrue)
  1347. return $this;
  1348. $this->sql .= " = " . $this->quote($value);
  1349. return $this;
  1350. }
  1351. /**
  1352. * Create '!='.
  1353. *
  1354. * @param string $value
  1355. * @access public
  1356. * @return void the sql object.
  1357. */
  1358. public function ne($value) {
  1359. if ($this->inCondition and!$this->conditionIsTrue)
  1360. return $this;
  1361. $this->sql .= " != " . $this->quote($value);
  1362. return $this;
  1363. }
  1364. /**
  1365. * Create '>'.
  1366. *
  1367. * @param string $value
  1368. * @access public
  1369. * @return object the sql object.
  1370. */
  1371. public function gt($value) {
  1372. if ($this->inCondition and!$this->conditionIsTrue)
  1373. return $this;
  1374. $this->sql .= " > " . $this->quote($value);
  1375. return $this;
  1376. }
  1377. /**
  1378. * Create '>='.
  1379. *
  1380. * @param string $value
  1381. * @access public
  1382. * @return object the sql object.
  1383. */
  1384. public function ge($value) {
  1385. if ($this->inCondition and!$this->conditionIsTrue)
  1386. return $this;
  1387. $this->sql .= " >= " . $this->quote($value);
  1388. return $this;
  1389. }
  1390. /**
  1391. * Create '<'.
  1392. *
  1393. * @param mixed $value
  1394. * @access public
  1395. * @return object the sql object.
  1396. */
  1397. public function lt($value) {
  1398. if ($this->inCondition and!$this->conditionIsTrue)
  1399. return $this;
  1400. $this->sql .= " < " . $this->quote($value);
  1401. return $this;
  1402. }
  1403. /**
  1404. * Create '<='.
  1405. *
  1406. * @param mixed $value
  1407. * @access public
  1408. * @return object the sql object.
  1409. */
  1410. public function le($value) {
  1411. if ($this->inCondition && !$this->conditionIsTrue) {
  1412. return $this;
  1413. }
  1414. $this->sql .= " <= " . $this->quote($value);
  1415. return $this;
  1416. }
  1417. /**
  1418. * Create "between and"
  1419. *
  1420. * @param string $min
  1421. * @param string $max
  1422. * @access public
  1423. * @return object the sql object.
  1424. */
  1425. public function between($min, $max) {
  1426. if ($this->inCondition and!$this->conditionIsTrue)
  1427. return $this;
  1428. $min = $this->quote($min);
  1429. $max = $this->quote($max);
  1430. $this->sql .= " BETWEEN $min AND $max ";
  1431. return $this;
  1432. }
  1433. /**
  1434. * Create in part.
  1435. *
  1436. * @param string|array $ids list string by ',' or an array
  1437. * @access public
  1438. * @return object the sql object.
  1439. */
  1440. public function in($ids) {
  1441. // var_dump($ids);
  1442. if ($this->inCondition and!$this->conditionIsTrue)
  1443. return $this;
  1444. $this->sql .= self::dbIN($ids);
  1445. return $this;
  1446. }
  1447. /**
  1448. * Create the in('a', 'b') string.
  1449. *
  1450. * @param string|array $ids the id lists, can be a array or a string with ids joined with comma.
  1451. * @static
  1452. * @access public
  1453. * @return string the string like IN('a', 'b').
  1454. */
  1455. private static function dbIN($ids) {
  1456. if (is_array($ids))
  1457. return "IN ('" . join("','", $ids) . "')";
  1458. return "IN ('" . str_replace(',', "','", str_replace(' ', '', $ids)) . "')";
  1459. }
  1460. /**
  1461. * Create not in part.
  1462. *
  1463. * @param string|array $ids list string by ',' or an array
  1464. * @access public
  1465. * @return object the sql object.
  1466. */
  1467. public function notin($ids) {
  1468. if ($this->inCondition and!$this->conditionIsTrue)
  1469. return $this;
  1470. $this->sql .= ' NOT ' . self::dbIN($ids);
  1471. return $this;
  1472. }
  1473. /**
  1474. * Create the like by part.
  1475. *
  1476. * @param string $string
  1477. * @access public
  1478. * @return object the sql object.
  1479. */
  1480. public function like($string) {
  1481. if ($this->inCondition and!$this->conditionIsTrue)
  1482. return $this;
  1483. $this->sql .= " LIKE " . $this->quote($string);
  1484. return $this;
  1485. }
  1486. /**
  1487. * Create the not like by part.
  1488. *
  1489. * @param string $string
  1490. * @access public
  1491. * @return object the sql object.
  1492. */
  1493. public function notLike($string) {
  1494. if ($this->inCondition and!$this->conditionIsTrue)
  1495. return $this;
  1496. $this->sql .= "NOT LIKE " . $this->quote($string);
  1497. return $this;
  1498. }
  1499. /**
  1500. * Create the find_in_set by part.
  1501. *
  1502. * @param int $str
  1503. * @param int $strList
  1504. * @access public
  1505. * @return object the sql object.
  1506. */
  1507. public function findInSet($str, $strList) {
  1508. if ($this->inCondition and!$this->conditionIsTrue)
  1509. return $this;
  1510. $this->sql .= "FIND_IN_SET(" . $str . "," . $strList . ")";
  1511. }
  1512. /**
  1513. * Create the order by part.
  1514. *
  1515. * @param string $order
  1516. * @access public
  1517. * @return object the sql object.
  1518. */
  1519. public function orderBy($order) {
  1520. if ($this->inCondition and!$this->conditionIsTrue)
  1521. return $this;
  1522. $order = str_replace(array('|', '', '_'), ' ', $order);
  1523. /* Add "`" in order string. */
  1524. /* When order has limit string. */
  1525. $pos = stripos($order, 'limit');
  1526. $orders = $pos ? substr($order, 0, $pos) : $order;
  1527. $limit = $pos ? substr($order, $pos) : '';
  1528. $orders = explode(',', $orders);
  1529. foreach ($orders as $i => $order) {
  1530. $orderParse = explode(' ', trim($order));
  1531. foreach ($orderParse as $key => $value) {
  1532. $value = trim($value);
  1533. if (empty($value) or strtolower($value) == 'desc' or strtolower($value) == 'asc')
  1534. continue;
  1535. $field = trim($value, '`');
  1536. /* such as t1.id field. */
  1537. if (strpos($value, '.') !== false)
  1538. list($table, $field) = explode('.', $field);
  1539. $field = "`$field`";
  1540. $orderParse[$key] = isset($table) ? $table . '.' . $field : $field;
  1541. unset($table);
  1542. }
  1543. $orders[$i] = join(' ', $orderParse);
  1544. }
  1545. $order = join(',', $orders) . ' ' . $limit;
  1546. $this->sql .= ' ' . DAO::ORDERBY . " $order";
  1547. return $this;
  1548. }
  1549. /**
  1550. * Create the limit part.
  1551. *
  1552. * @param string $limit
  1553. * @access public
  1554. * @return object the sql object.
  1555. */
  1556. public function limit($limit) {
  1557. if (empty($limit))
  1558. return $this;
  1559. stripos($limit, 'limit') !== false ? $this->sql .= " $limit " : $this->sql .= ' ' . DAO::LIMIT . " $limit ";
  1560. return $this;
  1561. }
  1562. /**
  1563. * Create the groupby part.
  1564. *
  1565. * @param string $groupBy
  1566. * @access public
  1567. * @return object the sql object.
  1568. */
  1569. public function groupBy($groupBy) {
  1570. $this->sql .= ' ' . DAO::GROUPBY . " $groupBy";
  1571. return $this;
  1572. }
  1573. /**
  1574. * Create the having part.
  1575. *
  1576. * @param string $having
  1577. * @access public
  1578. * @return object the sql object.
  1579. */
  1580. public function having($having) {
  1581. $this->sql .= ' ' . DAO::HAVING . " $having";
  1582. return $this;
  1583. }
  1584. /**
  1585. * Get the sql string.
  1586. *
  1587. * @access public
  1588. * @return string
  1589. */
  1590. public function get() {
  1591. return $this->sql;
  1592. }
  1593. /**
  1594. * Uuote a var.
  1595. *
  1596. * @param mixed $value
  1597. * @access public
  1598. * @return mixed
  1599. */
  1600. public function quote($value) {
  1601. // var_dump($value);
  1602. if ($this->magicQuote) {
  1603. $value = stripslashes($value);
  1604. }
  1605. return $this->dbh->quote($value);
  1606. }
  1607. }