dao.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  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. // var_dump($data);
  419. if (!is_object($data))
  420. $data = (object) $data;
  421. $this->sqlobj->data($data);
  422. return $this;
  423. }
  424. //-------------------- The sql related method. --------------------//
  425. /**
  426. * Get the sql string.
  427. *
  428. * @access public
  429. * @return string the sql string after process.
  430. */
  431. public function get() {
  432. return $this->processKeywords($this->processSQL());
  433. }
  434. /**
  435. * Print the sql string.
  436. *
  437. * @access public
  438. * @return void
  439. */
  440. public function printSQL() {
  441. echo $this->processSQL();
  442. }
  443. /**
  444. * Process the sql, replace the table, fields.
  445. *
  446. * @access private
  447. * @return string the sql string after process.
  448. */
  449. private function processSQL() {
  450. $sql = $this->sqlobj->get();
  451. /* If the mode is magic, process the $fields and $table. */
  452. if ($this->mode == 'magic') {
  453. if ($this->fields == '')
  454. $this->fields = '*';
  455. if ($this->table == '')
  456. $this->triggerError('Must set the table name', __FILE__, __LINE__, $exit = true);
  457. $sql = sprintf($this->sqlobj->get(), $this->fields, $this->table);
  458. }
  459. self::$querys[] = $this->processKeywords($sql);
  460. return $sql;
  461. }
  462. /**
  463. * Trriger an error.
  464. *
  465. * @param string $message error message
  466. * @param string $file the file error occers
  467. * @param int $line the line error occers
  468. * @param bool $exit exit the program or not
  469. * @access public
  470. * @return void
  471. */
  472. private function triggerError($message, $file, $line, $exit = false) {
  473. /* Set the error info. */
  474. $log = "ERROR: " . CommUtil::str2UTF8($message) . " in "
  475. . CommUtil::str2UTF8($file) . " on line $line";
  476. if (isset($_SERVER['SCRIPT_URI']))
  477. $log .= ", request: $_SERVER[SCRIPT_URI]";
  478. ;
  479. $trace = debug_backtrace();
  480. extract($trace[0]); # function
  481. extract($trace[1]); # line
  482. $log .= ", last called by $file on line $line through function $function.\n";
  483. // CLog::err($log, "dao");
  484. // CLog::err($trace, "dao");
  485. /* Trigger it. */
  486. trigger_error($log, $exit ? E_USER_ERROR : E_USER_WARNING);
  487. }
  488. /**
  489. * Process the sql keywords, replace the constants to normal.
  490. *
  491. * @param string $sql
  492. * @access private
  493. * @return string the sql string.
  494. */
  495. private function processKeywords($sql) {
  496. return str_replace(array(DAO::WHERE, DAO::GROUPBY, DAO::HAVING, DAO::ORDERBY, DAO::LIMIT), array('WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT'), $sql);
  497. }
  498. //-------------------- Query related methods. --------------------//
  499. /**
  500. * Set the dbh.
  501. *
  502. * You can use like this: $this->dao->dbh($dbh), thus you can handle two database.
  503. *
  504. * @param object $dbh
  505. * @access public
  506. * @return object the dao object self.
  507. */
  508. public function dbh($dbh) {
  509. $this->dbh = $dbh;
  510. return $this;
  511. }
  512. /**
  513. * Query the sql, return the statement object.
  514. *
  515. * @param string $sql
  516. * @access public
  517. * @return object the PDOStatement object.
  518. */
  519. public function query($sql = '') {
  520. if (!empty(dao::$errors))
  521. return new PDOStatement(); // If any error, return an empty statement object to make sure the remain method to execute.
  522. if ($sql) {
  523. if (is_null($this->sqlobj)) {
  524. $this->sqlobj = sql::factory();
  525. }
  526. $this->sqlobj->sql = $sql;
  527. }
  528. $sql = $this->processSQL();
  529. try {
  530. $method = $this->method;
  531. $this->reset();
  532. // var_dump($sql);
  533. if ($this->slaveDBH and $method == 'select') {
  534. return $this->slaveDBH->query($sql);
  535. } else {
  536. return $this->dbh->query($sql);
  537. }
  538. } catch (PDOException $e) {
  539. $this->sqlError($e);
  540. }
  541. }
  542. /**
  543. * Page the records, set the limit part auto.
  544. *
  545. * @param object $pager
  546. * @access public
  547. * @return object the dao object self.
  548. */
  549. public function page($pager) {
  550. if (!is_object($pager))
  551. return $this;
  552. /* If the record total is 0, compute it. */
  553. if ($pager->recTotal == 0) {
  554. /* Get the SELECT, FROM position, thus get the fields, replace it by count(*). */
  555. $sql = $this->get();
  556. $selectPOS = strpos($sql, 'SELECT') + strlen('SELECT');
  557. $fromPOS = strpos($sql, 'FROM');
  558. $fields = substr($sql, $selectPOS, $fromPOS - $selectPOS);
  559. $sql = str_replace($fields, ' COUNT(*) AS recTotal ', $sql);
  560. /* Remove the part after order and limit. */
  561. $subLength = strlen($sql);
  562. $orderPOS = strripos($sql, 'order ');
  563. $limitPOS = strripos($sql, 'limit');
  564. if ($limitPOS)
  565. $subLength = $limitPOS;
  566. if ($orderPOS)
  567. $subLength = $orderPOS;
  568. $sql = substr($sql, 0, $subLength);
  569. self::$querys[] = $sql;
  570. /* Get the records count. */
  571. try {
  572. $row = $this->dbh->query($sql)->fetch(PDO::FETCH_OBJ);
  573. } catch (PDOException $e) {
  574. $this->sqlError($e);
  575. }
  576. $pager->setRecTotal($row->recTotal);
  577. $pager->setPageTotal();
  578. }
  579. $this->sqlobj->limit($pager->limit());
  580. return $this;
  581. }
  582. /**
  583. * Execute the sql. It's different with query(), which return the stmt object. But this not.
  584. *
  585. * @param string $sql
  586. * @access public
  587. * @return int the modified or deleted records.
  588. */
  589. public function exec($sql = '') {
  590. if (!empty(dao::$errors))
  591. return new PDOStatement(); // If any error, return an empty statement object to make sure the remain method to execute.
  592. // var_dump($sql);
  593. if ($sql) {
  594. if (is_null($this->sqlobj)) {
  595. $this->sqlobj = sql::factory();
  596. }
  597. $this->sqlobj->sql = $sql;
  598. }
  599. $sql = $this->processSQL();
  600. try {
  601. $this->reset();
  602. return $this->dbh->exec($sql);
  603. } catch (PDOException $e) {
  604. $this->sqlError($e);
  605. }
  606. }
  607. //-------------------- Fetch related methods. -------------------//
  608. /**
  609. * Fetch one record.
  610. *
  611. * @param string $field if the field is set, only return the value of this field, else return this record
  612. * @access public
  613. * @return object|mixed
  614. */
  615. public function fetch($field = '') {
  616. if (empty($field))
  617. return $this->query()->fetch();
  618. $this->setFields($field);
  619. $result = $this->query()->fetch(PDO::FETCH_OBJ);
  620. if ($result)
  621. return $result->$field;
  622. }
  623. /**
  624. * Fetch all records.
  625. *
  626. * @param string $keyField the key field, thus the return records is keyed by this field
  627. * @access public
  628. * @return array the records
  629. */
  630. public function fetchAll($keyField = '') {
  631. $stmt = $this->query();
  632. if (empty($keyField))
  633. return $stmt->fetchAll();
  634. $rows = array();
  635. while ($row = $stmt->fetch())
  636. $rows[$row->$keyField] = $row;
  637. return $rows;
  638. }
  639. /**
  640. * Fetch all records and group them by one field.
  641. *
  642. * @param string $groupField the field to group by
  643. * @param string $keyField the field of key
  644. * @access public
  645. * @return array the records.
  646. */
  647. public function fetchGroup($groupField, $keyField = '') {
  648. $stmt = $this->query();
  649. $rows = array();
  650. while ($row = $stmt->fetch()) {
  651. empty($keyField) ? $rows[$row->$groupField][] = $row : $rows[$row->$groupField][$row->$keyField] = $row;
  652. }
  653. return $rows;
  654. }
  655. /**
  656. * Fetch array like key=>value.
  657. *
  658. * If the keyFiled and valueField not set, use the first and last in the record.
  659. *
  660. * @param string $keyField
  661. * @param string $valueField
  662. * @access public
  663. * @return array
  664. */
  665. public function fetchPairs($keyField = '', $valueField = '') {
  666. $pairs = array();
  667. $ready = false;
  668. $stmt = $this->query();
  669. while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  670. if (!$ready) {
  671. if (empty($keyField))
  672. $keyField = key($row);
  673. if (empty($valueField)) {
  674. end($row);
  675. $valueField = key($row);
  676. }
  677. $ready = true;
  678. }
  679. $pairs[$row[$keyField]] = $row[$valueField];
  680. }
  681. return $pairs;
  682. }
  683. /**
  684. * Return the last insert ID.
  685. *
  686. * @access public
  687. * @return int
  688. */
  689. public function lastInsertID() {
  690. return $this->dbh->lastInsertID();
  691. }
  692. //-------------------- Magic methods.--------------------//
  693. /**
  694. * Use it to do some convenient queries.
  695. *
  696. * @param string $funcName the function name to be called
  697. * @param array $funcArgs the params
  698. * @access public
  699. * @return object the dao object self.
  700. */
  701. public function __call($funcName, $funcArgs) {
  702. $funcName = strtolower($funcName);
  703. /* findByxxx, xxx as will be in the where. */
  704. if (strpos($funcName, 'findby') !== false) {
  705. $this->setMode('magic');
  706. $field = str_replace('findby', '', $funcName);
  707. if (count($funcArgs) == 1) {
  708. $operator = '=';
  709. $value = $funcArgs[0];
  710. } else {
  711. $operator = $funcArgs[0];
  712. $value = $funcArgs[1];
  713. }
  714. $this->sqlobj = sql::select('%s')->from('%s')->where($field, $operator, $value);
  715. return $this;
  716. }
  717. /* Fetch10. */ elseif (strpos($funcName, 'fetch') !== false) {
  718. $max = str_replace('fetch', '', $funcName);
  719. $stmt = $this->query();
  720. $rows = array();
  721. $key = isset($funcArgs[0]) ? $funcArgs[0] : '';
  722. $i = 0;
  723. while ($row = $stmt->fetch()) {
  724. $key ? $rows[$row->$key] = $row : $rows[] = $row;
  725. $i++;
  726. if ($i == $max)
  727. break;
  728. }
  729. return $rows;
  730. }
  731. /* Others, call the method in sql class. */ else {
  732. /* Create the max counts of sql class methods, and then create $arg0, $arg1... */
  733. for ($i = 0; $i < SQL::MAX_ARGS; $i++) {
  734. ${"arg$i"} = isset($funcArgs[$i]) ? $funcArgs[$i] : null;
  735. }
  736. $this->sqlobj->$funcName($arg0, $arg1, $arg2);
  737. return $this;
  738. }
  739. }
  740. //-------------------- Checking.--------------------//
  741. /**
  742. * Check a filed is satisfied with the check rule.
  743. *
  744. * @param string $fieldName the field to check
  745. * @param string $funcName the check rule
  746. * @access public
  747. * @return object the dao object self.
  748. */
  749. public function check($fieldName, $funcName) {
  750. /* If no this field in the data, reuturn. */
  751. if (!isset($this->sqlobj->data->$fieldName))
  752. return $this;
  753. /* Set the field label and value. */
  754. global $lang, $config, $app;
  755. $table = strtolower(str_replace(array($config->db->prefix, '`'), '', $this->table));
  756. $fieldLabel = isset($lang->$table->$fieldName) ? $lang->$table->$fieldName : $fieldName;
  757. $value = $this->sqlobj->data->$fieldName;
  758. /* Check unique. */
  759. if ($funcName == 'unique') {
  760. $args = func_get_args();
  761. $sql = "SELECT COUNT(*) AS count FROM $this->table WHERE `$fieldName` = " . $this->sqlobj->quote($value);
  762. if (isset($args[2]))
  763. $sql .= ' AND ' . $args[2];
  764. try {
  765. $row = $this->dbh->query($sql)->fetch();
  766. if ($row->count != 0)
  767. $this->logError($funcName, $fieldName, $fieldLabel, array($value));
  768. } catch (PDOException $e) {
  769. $this->sqlError($e);
  770. }
  771. } else {
  772. /* Create the params. */
  773. $funcArgs = func_get_args();
  774. unset($funcArgs[0]);
  775. unset($funcArgs[1]);
  776. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  777. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  778. }
  779. $checkFunc = 'check' . $funcName;
  780. if (validater::$checkFunc($value, $arg0, $arg1, $arg2) === false) {
  781. $this->logError($funcName, $fieldName, $fieldLabel, $funcArgs);
  782. }
  783. }
  784. return $this;
  785. }
  786. /**
  787. * Check a field, if satisfied with the condition.
  788. *
  789. * @param string $condition
  790. * @param string $fieldName
  791. * @param string $funcName
  792. * @access public
  793. * @return object the dao object self.
  794. */
  795. public function checkIF($condition, $fieldName, $funcName) {
  796. if (!$condition)
  797. return $this;
  798. $funcArgs = func_get_args();
  799. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  800. ${"arg$i"} = isset($funcArgs[$i + 3]) ? $funcArgs[$i + 3] : null;
  801. }
  802. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  803. return $this;
  804. }
  805. /**
  806. * Batch check some fileds.
  807. *
  808. * @param string $fields the fields to check, join with ,
  809. * @param string $funcName
  810. * @access public
  811. * @return object the dao object self.
  812. */
  813. public function batchCheck($fields, $funcName) {
  814. $fields = explode(',', str_replace(' ', '', $fields));
  815. $funcArgs = func_get_args();
  816. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  817. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  818. }
  819. foreach ($fields as $fieldName)
  820. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  821. return $this;
  822. }
  823. /**
  824. * Batch check fields on the condition is true.
  825. *
  826. * @param string $condition
  827. * @param string $fields
  828. * @param string $funcName
  829. * @access public
  830. * @return object the dao object self.
  831. */
  832. public function batchCheckIF($condition, $fields, $funcName) {
  833. if (!$condition)
  834. return $this;
  835. $fields = explode(',', str_replace(' ', '', $fields));
  836. $funcArgs = func_get_args();
  837. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  838. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  839. }
  840. foreach ($fields as $fieldName)
  841. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  842. return $this;
  843. }
  844. /**
  845. * Check the fields according the the database schema.
  846. *
  847. * @param string $skipFields fields to skip checking
  848. * @access public
  849. * @return object the dao object self.
  850. */
  851. public function autoCheck($skipFields = '') {
  852. $fields = $this->getFieldsType();
  853. $skipFields = ",$skipFields,";
  854. foreach ($fields as $fieldName => $validater) {
  855. if (strpos($skipFields, $fieldName) !== false)
  856. continue; // skip it.
  857. if (!isset($this->sqlobj->data->$fieldName))
  858. continue;
  859. if ($validater['rule'] == 'skip')
  860. continue;
  861. $options = array();
  862. if (isset($validater['options']))
  863. $options = array_values($validater['options']);
  864. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  865. ${"arg$i"} = isset($options[$i]) ? $options[$i] : null;
  866. }
  867. $this->check($fieldName, $validater['rule'], $arg0, $arg1, $arg2);
  868. }
  869. return $this;
  870. }
  871. /**
  872. * 检查表是否存在
  873. * @param type $tableName
  874. * @return type
  875. */
  876. public function tableExist($tableName) {
  877. $this->reset();
  878. $this->setMethod('select');
  879. $sql = "SELECT 1 FROM $tableName LIMIT 1";
  880. try {
  881. if ($this->slaveDBH and $this->method == 'select') {
  882. $ret = $this->slaveDBH->query($sql)->fetch();
  883. } else {
  884. $ret = $this->dbh->query($sql)->fetch();
  885. }
  886. } catch (Exception $exc) {
  887. return false;
  888. }
  889. // Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
  890. return $ret !== FALSE; # false代表表不存在
  891. }
  892. /**
  893. * Log the error.
  894. *
  895. * For the error notice, see module/common/lang.
  896. *
  897. * @param string $checkType the check rule
  898. * @param string $fieldName the field name
  899. * @param string $fieldLabel the field label
  900. * @param array $funcArgs the args
  901. * @access public
  902. * @return void
  903. */
  904. public function logError($checkType, $fieldName, $fieldLabel, $funcArgs = array()) {
  905. global $lang;
  906. $error = $lang->error->$checkType;
  907. $replaces = array_merge(array($fieldLabel), $funcArgs); // the replace values.
  908. /* Just a string, cycle the $replaces. */
  909. if (!is_array($error)) {
  910. foreach ($replaces as $replace) {
  911. $pos = strpos($error, '%s');
  912. if ($pos === false)
  913. break;
  914. $error = substr($error, 0, $pos) . $replace . substr($error, $pos + 2);
  915. }
  916. }
  917. /* If the error define is an array, select the one which %s counts match the $replaces. */ else {
  918. /* Remove the empty items. */
  919. foreach ($replaces as $key => $value)
  920. if (is_null($value))
  921. unset($replaces[$key]);
  922. $replacesCount = count($replaces);
  923. foreach ($error as $errorString) {
  924. if (substr_count($errorString, '%s') == $replacesCount) {
  925. $error = vsprintf($errorString, $replaces);
  926. }
  927. }
  928. }
  929. dao::$errors[$fieldName][] = $error;
  930. }
  931. /**
  932. * Judge any error or not.
  933. *
  934. * @access public
  935. * @return bool
  936. */
  937. public static function isError() {
  938. return !empty(dao::$errors);
  939. }
  940. /**
  941. * Get the errors.
  942. *
  943. * @param boolean $join
  944. * @access public
  945. * @return array
  946. */
  947. public static function getError($join = false) {
  948. $errors = dao::$errors;
  949. dao::$errors = array(); // Must clear it.
  950. if (!$join)
  951. return $errors;
  952. if (is_array($errors)) {
  953. $message = '';
  954. foreach ($errors as $item) {
  955. is_array($item) ? $message .= join('\n', $item) . '\n' : $message .= $item . '\n';
  956. }
  957. return $message;
  958. }
  959. }
  960. /**
  961. * Get the defination of fields of the table.
  962. *
  963. * @access private
  964. * @return array
  965. */
  966. private function getFieldsType() {
  967. try {
  968. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
  969. $sql = "DESC $this->table";
  970. $rawFields = $this->dbh->query($sql)->fetchAll();
  971. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  972. } catch (PDOException $e) {
  973. $this->sqlError($e);
  974. }
  975. foreach ($rawFields as $rawField) {
  976. $firstPOS = strpos($rawField->type, '(');
  977. $type = substr($rawField->type, 0, $firstPOS > 0 ? $firstPOS : strlen($rawField->type));
  978. $type = str_replace(array('big', 'small', 'medium', 'tiny', 'var'), '', $type);
  979. $field = array();
  980. if ($type == 'enum' or $type == 'set') {
  981. $rangeBegin = $firstPOS + 2; // Remove the first quote.
  982. $rangeEnd = strrpos($rawField->type, ')') - 1; // Remove the last quote.
  983. $range = substr($rawField->type, $rangeBegin, $rangeEnd - $rangeBegin);
  984. $field['rule'] = 'reg';
  985. $field['options']['reg'] = '/' . str_replace("','", '|', $range) . '/';
  986. } elseif ($type == 'char') {
  987. $begin = $firstPOS + 1;
  988. $end = strpos($rawField->type, ')', $begin);
  989. $length = substr($rawField->type, $begin, $end - $begin);
  990. $field['rule'] = 'length';
  991. $field['options']['max'] = $length;
  992. $field['options']['min'] = 0;
  993. } elseif ($type == 'int') {
  994. $field['rule'] = 'int';
  995. } elseif ($type == 'float' or $type == 'double') {
  996. $field['rule'] = 'float';
  997. } elseif ($type == 'date') {
  998. $field['rule'] = 'date';
  999. } else {
  1000. $field['rule'] = 'skip';
  1001. }
  1002. $fields[$rawField->field] = $field;
  1003. }
  1004. return $fields;
  1005. }
  1006. /**
  1007. * Process SQL error by code.
  1008. *
  1009. * @param object $exception
  1010. * @access public
  1011. * @return void
  1012. */
  1013. public function sqlError($exception) {
  1014. $errorInfo = $exception->errorInfo;
  1015. $errorCode = $errorInfo[1];
  1016. $errorMsg = $errorInfo[2];
  1017. $message = $exception->getMessage();
  1018. if (strpos($this->repairCode, "|$errorCode|") !== false #
  1019. or ( $errorCode == '1016' and strpos($errorMsg, 'errno: 145') !== false)) {
  1020. $message .= ' repairTable';
  1021. }
  1022. $sql = $this->sqlobj->get();
  1023. $this->triggerError($message . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
  1024. }
  1025. }
  1026. /**
  1027. * The SQL class.
  1028. *
  1029. * @package framework
  1030. */
  1031. class sql {
  1032. /**
  1033. * The max count of params of all methods.
  1034. *
  1035. */
  1036. const MAX_ARGS = 3;
  1037. /**
  1038. * The sql string.
  1039. *
  1040. * @var string
  1041. * @access public
  1042. */
  1043. public $sql = '';
  1044. /**
  1045. * The global $dbh.
  1046. *
  1047. *
  1048. * @access protected
  1049. */
  1050. protected $dbh;
  1051. /**
  1052. * The data to update or insert.
  1053. *
  1054. * @var mix
  1055. * @access protected
  1056. */
  1057. public $data;
  1058. /**
  1059. * Is the first time to call set.
  1060. *
  1061. * @var bool
  1062. * @access private;
  1063. */
  1064. private $isFirstSet = true;
  1065. /**
  1066. * If in the logic of judge condition or not.
  1067. *
  1068. * @var bool
  1069. * @access private;
  1070. */
  1071. private $inCondition = false;
  1072. /**
  1073. * The condition is true or not.
  1074. *
  1075. * @var bool
  1076. * @access private;
  1077. */
  1078. private $conditionIsTrue = false;
  1079. /**
  1080. * Magic quote or not.
  1081. *
  1082. * @var bool
  1083. * @access public
  1084. */
  1085. public $magicQuote;
  1086. /**
  1087. * The construct function. user factory() to instance it.
  1088. *
  1089. * @param string $table
  1090. * @access private
  1091. * @return void
  1092. */
  1093. private function __construct($table = '') {
  1094. global $dbh;
  1095. $this->dbh = $dbh;
  1096. $this->magicQuote = false; // get_magic_quotes_gpc();
  1097. }
  1098. /**
  1099. * The factory method.
  1100. *
  1101. * @param string $table
  1102. * @access public
  1103. * @return object the sql object.
  1104. */
  1105. public static function factory($table = '') {
  1106. return new sql($table);
  1107. }
  1108. /**
  1109. * The sql is select.
  1110. *
  1111. * @param string $field
  1112. * @access public
  1113. * @return object the sql object.
  1114. */
  1115. public static function select($field = '*') {
  1116. $sqlobj = self::factory();
  1117. $sqlobj->sql = "SELECT $field ";
  1118. return $sqlobj;
  1119. }
  1120. /**
  1121. * The sql is update.
  1122. *
  1123. * @param string $table
  1124. * @access public
  1125. * @return object the sql object.
  1126. */
  1127. public static function update($table) {
  1128. $sqlobj = self::factory();
  1129. $sqlobj->sql = "UPDATE $table SET ";
  1130. return $sqlobj;
  1131. }
  1132. /**
  1133. * The sql is insert.
  1134. *
  1135. * @param string $table
  1136. * @access public
  1137. * @return object the sql object.
  1138. */
  1139. public static function insert($table) {
  1140. $sqlobj = self::factory();
  1141. $sqlobj->sql = "INSERT INTO $table SET ";
  1142. return $sqlobj;
  1143. }
  1144. /**
  1145. * The sql is replace.
  1146. *
  1147. * @param string $table
  1148. * @access public
  1149. * @return object the sql object.
  1150. */
  1151. public static function replace($table) {
  1152. $sqlobj = self::factory();
  1153. $sqlobj->sql = "REPLACE $table SET ";
  1154. return $sqlobj;
  1155. }
  1156. /**
  1157. * The sql is delete.
  1158. *
  1159. * @access public
  1160. * @return object the sql object.
  1161. */
  1162. public static function delete() {
  1163. $sqlobj = self::factory();
  1164. $sqlobj->sql = "DELETE ";
  1165. return $sqlobj;
  1166. }
  1167. /**
  1168. * Join the data items by key = value.
  1169. *
  1170. * @param object $data
  1171. * @access public
  1172. * @return object the sql object.
  1173. */
  1174. public function data($data) {
  1175. // var_dump($data);
  1176. loyalsoft\DebugHelper::
  1177. $data = (object) $data;
  1178. foreach ($data as $field => $value) {
  1179. if (!preg_match('|^\w+$|', $field)) {
  1180. unset($data->$field);
  1181. continue;
  1182. }
  1183. $this->sql .= "`$field` = " . $this->quote($value) . ',';
  1184. }
  1185. $this->data = $data;
  1186. $this->sql = rtrim($this->sql, ','); // Remove the last ','.
  1187. return $this;
  1188. }
  1189. /**
  1190. * Aadd an '(' at left.
  1191. *
  1192. * @param int $count
  1193. * @access public
  1194. * @return ojbect the sql object.
  1195. */
  1196. public function markLeft($count = 1) {
  1197. $this->sql .= str_repeat('(', $count);
  1198. return $this;
  1199. }
  1200. /**
  1201. * Add an ')' ad right.
  1202. *
  1203. * @param int $count
  1204. * @access public
  1205. * @return object the sql object.
  1206. */
  1207. public function markRight($count = 1) {
  1208. $this->sql .= str_repeat(')', $count);
  1209. return $this;
  1210. }
  1211. /**
  1212. * The set part.
  1213. *
  1214. * @param string $set
  1215. * @access public
  1216. * @return object the sql object.
  1217. */
  1218. public function set($set) {
  1219. if ($this->isFirstSet) {
  1220. $this->sql .= " $set ";
  1221. $this->isFirstSet = false;
  1222. } else {
  1223. $this->sql .= ", $set";
  1224. }
  1225. return $this;
  1226. }
  1227. /**
  1228. * Create the from part.
  1229. *
  1230. * @param string $table
  1231. * @access public
  1232. * @return object the sql object.
  1233. */
  1234. public function from($table) {
  1235. $this->sql .= "FROM $table";
  1236. return $this;
  1237. }
  1238. /**
  1239. * Create the Alias part.
  1240. *
  1241. * @param string $alias
  1242. * @access public
  1243. * @return object the sql object.
  1244. */
  1245. public function alias($alias) {
  1246. $this->sql .= " AS $alias ";
  1247. return $this;
  1248. }
  1249. /**
  1250. * Create the left join part.
  1251. *
  1252. * @param string $table
  1253. * @access public
  1254. * @return object the sql object.
  1255. */
  1256. public function leftJoin($table) {
  1257. $this->sql .= " LEFT JOIN $table";
  1258. return $this;
  1259. }
  1260. /**
  1261. * Create the on part.
  1262. *
  1263. * @param string $condition
  1264. * @access public
  1265. * @return object the sql object.
  1266. */
  1267. public function on($condition) {
  1268. $this->sql .= " ON $condition ";
  1269. return $this;
  1270. }
  1271. /**
  1272. * Begin condition judge.
  1273. *
  1274. * @param bool $condition
  1275. * @access public
  1276. * @return object the sql object.
  1277. */
  1278. public function beginIF($condition) {
  1279. $this->inCondition = true;
  1280. $this->conditionIsTrue = $condition;
  1281. return $this;
  1282. }
  1283. /**
  1284. * End the condition judge.
  1285. *
  1286. * @access public
  1287. * @return object the sql object.
  1288. */
  1289. public function fi() {
  1290. $this->inCondition = false;
  1291. $this->conditionIsTrue = false;
  1292. return $this;
  1293. }
  1294. /**
  1295. * Create the where part.
  1296. *
  1297. * @param string $arg1 the field name
  1298. * @param string $arg2 the operator
  1299. * @param string $arg3 the value
  1300. * @access public
  1301. * @return object the sql object.
  1302. */
  1303. public function where($arg1, $arg2 = null, $arg3 = null) {
  1304. if ($this->inCondition and!$this->conditionIsTrue)
  1305. return $this;
  1306. if ($arg3 !== null) {
  1307. $value = $this->quote($arg3);
  1308. $condition = "`$arg1` $arg2 " . $this->quote($arg3);
  1309. } else {
  1310. $condition = $arg1;
  1311. }
  1312. $this->sql .= ' ' . DAO::WHERE . " $condition ";
  1313. return $this;
  1314. }
  1315. /**
  1316. * Create the AND part.
  1317. *
  1318. * @param string $condition
  1319. * @access public
  1320. * @return object the sql object.
  1321. */
  1322. public function andWhere($condition) {
  1323. if ($this->inCondition and!$this->conditionIsTrue)
  1324. return $this;
  1325. $this->sql .= " AND $condition ";
  1326. return $this;
  1327. }
  1328. /**
  1329. * Create the OR part.
  1330. *
  1331. * @param bool $condition
  1332. * @access public
  1333. * @return object the sql object.
  1334. */
  1335. public function orWhere($condition) {
  1336. if ($this->inCondition and!$this->conditionIsTrue)
  1337. return $this;
  1338. $this->sql .= " OR $condition ";
  1339. return $this;
  1340. }
  1341. /**
  1342. * Create the '='.
  1343. *
  1344. * @param string $value
  1345. * @access public
  1346. * @return object the sql object.
  1347. */
  1348. public function eq($value) {
  1349. if ($this->inCondition and!$this->conditionIsTrue)
  1350. return $this;
  1351. $this->sql .= " = " . $this->quote($value);
  1352. return $this;
  1353. }
  1354. /**
  1355. * Create '!='.
  1356. *
  1357. * @param string $value
  1358. * @access public
  1359. * @return void the sql object.
  1360. */
  1361. public function ne($value) {
  1362. if ($this->inCondition and!$this->conditionIsTrue)
  1363. return $this;
  1364. $this->sql .= " != " . $this->quote($value);
  1365. return $this;
  1366. }
  1367. /**
  1368. * Create '>'.
  1369. *
  1370. * @param string $value
  1371. * @access public
  1372. * @return object the sql object.
  1373. */
  1374. public function gt($value) {
  1375. if ($this->inCondition and!$this->conditionIsTrue)
  1376. return $this;
  1377. $this->sql .= " > " . $this->quote($value);
  1378. return $this;
  1379. }
  1380. /**
  1381. * Create '>='.
  1382. *
  1383. * @param string $value
  1384. * @access public
  1385. * @return object the sql object.
  1386. */
  1387. public function ge($value) {
  1388. if ($this->inCondition and!$this->conditionIsTrue)
  1389. return $this;
  1390. $this->sql .= " >= " . $this->quote($value);
  1391. return $this;
  1392. }
  1393. /**
  1394. * Create '<'.
  1395. *
  1396. * @param mixed $value
  1397. * @access public
  1398. * @return object the sql object.
  1399. */
  1400. public function lt($value) {
  1401. if ($this->inCondition and!$this->conditionIsTrue)
  1402. return $this;
  1403. $this->sql .= " < " . $this->quote($value);
  1404. return $this;
  1405. }
  1406. /**
  1407. * Create '<='.
  1408. *
  1409. * @param mixed $value
  1410. * @access public
  1411. * @return object the sql object.
  1412. */
  1413. public function le($value) {
  1414. if ($this->inCondition && !$this->conditionIsTrue) {
  1415. return $this;
  1416. }
  1417. $this->sql .= " <= " . $this->quote($value);
  1418. return $this;
  1419. }
  1420. /**
  1421. * Create "between and"
  1422. *
  1423. * @param string $min
  1424. * @param string $max
  1425. * @access public
  1426. * @return object the sql object.
  1427. */
  1428. public function between($min, $max) {
  1429. if ($this->inCondition and!$this->conditionIsTrue)
  1430. return $this;
  1431. $min = $this->quote($min);
  1432. $max = $this->quote($max);
  1433. $this->sql .= " BETWEEN $min AND $max ";
  1434. return $this;
  1435. }
  1436. /**
  1437. * Create in part.
  1438. *
  1439. * @param string|array $ids list string by ',' or an array
  1440. * @access public
  1441. * @return object the sql object.
  1442. */
  1443. public function in($ids) {
  1444. // var_dump($ids);
  1445. if ($this->inCondition and!$this->conditionIsTrue)
  1446. return $this;
  1447. $this->sql .= self::dbIN($ids);
  1448. return $this;
  1449. }
  1450. /**
  1451. * Create the in('a', 'b') string.
  1452. *
  1453. * @param string|array $ids the id lists, can be a array or a string with ids joined with comma.
  1454. * @static
  1455. * @access public
  1456. * @return string the string like IN('a', 'b').
  1457. */
  1458. private static function dbIN($ids) {
  1459. if (is_array($ids))
  1460. return "IN ('" . join("','", $ids) . "')";
  1461. return "IN ('" . str_replace(',', "','", str_replace(' ', '', $ids)) . "')";
  1462. }
  1463. /**
  1464. * Create not in part.
  1465. *
  1466. * @param string|array $ids list string by ',' or an array
  1467. * @access public
  1468. * @return object the sql object.
  1469. */
  1470. public function notin($ids) {
  1471. if ($this->inCondition and!$this->conditionIsTrue)
  1472. return $this;
  1473. $this->sql .= ' NOT ' . self::dbIN($ids);
  1474. return $this;
  1475. }
  1476. /**
  1477. * Create the like by part.
  1478. *
  1479. * @param string $string
  1480. * @access public
  1481. * @return object the sql object.
  1482. */
  1483. public function like($string) {
  1484. if ($this->inCondition and!$this->conditionIsTrue)
  1485. return $this;
  1486. $this->sql .= " LIKE " . $this->quote($string);
  1487. return $this;
  1488. }
  1489. /**
  1490. * Create the not like by part.
  1491. *
  1492. * @param string $string
  1493. * @access public
  1494. * @return object the sql object.
  1495. */
  1496. public function notLike($string) {
  1497. if ($this->inCondition and!$this->conditionIsTrue)
  1498. return $this;
  1499. $this->sql .= "NOT LIKE " . $this->quote($string);
  1500. return $this;
  1501. }
  1502. /**
  1503. * Create the find_in_set by part.
  1504. *
  1505. * @param int $str
  1506. * @param int $strList
  1507. * @access public
  1508. * @return object the sql object.
  1509. */
  1510. public function findInSet($str, $strList) {
  1511. if ($this->inCondition and!$this->conditionIsTrue)
  1512. return $this;
  1513. $this->sql .= "FIND_IN_SET(" . $str . "," . $strList . ")";
  1514. }
  1515. /**
  1516. * Create the order by part.
  1517. *
  1518. * @param string $order
  1519. * @access public
  1520. * @return object the sql object.
  1521. */
  1522. public function orderBy($order) {
  1523. if ($this->inCondition and!$this->conditionIsTrue)
  1524. return $this;
  1525. $order = str_replace(array('|', '', '_'), ' ', $order);
  1526. /* Add "`" in order string. */
  1527. /* When order has limit string. */
  1528. $pos = stripos($order, 'limit');
  1529. $orders = $pos ? substr($order, 0, $pos) : $order;
  1530. $limit = $pos ? substr($order, $pos) : '';
  1531. $orders = explode(',', $orders);
  1532. foreach ($orders as $i => $order) {
  1533. $orderParse = explode(' ', trim($order));
  1534. foreach ($orderParse as $key => $value) {
  1535. $value = trim($value);
  1536. if (empty($value) or strtolower($value) == 'desc' or strtolower($value) == 'asc')
  1537. continue;
  1538. $field = trim($value, '`');
  1539. /* such as t1.id field. */
  1540. if (strpos($value, '.') !== false)
  1541. list($table, $field) = explode('.', $field);
  1542. $field = "`$field`";
  1543. $orderParse[$key] = isset($table) ? $table . '.' . $field : $field;
  1544. unset($table);
  1545. }
  1546. $orders[$i] = join(' ', $orderParse);
  1547. }
  1548. $order = join(',', $orders) . ' ' . $limit;
  1549. $this->sql .= ' ' . DAO::ORDERBY . " $order";
  1550. return $this;
  1551. }
  1552. /**
  1553. * Create the limit part.
  1554. *
  1555. * @param string $limit
  1556. * @access public
  1557. * @return object the sql object.
  1558. */
  1559. public function limit($limit) {
  1560. if (empty($limit))
  1561. return $this;
  1562. stripos($limit, 'limit') !== false ? $this->sql .= " $limit " : $this->sql .= ' ' . DAO::LIMIT . " $limit ";
  1563. return $this;
  1564. }
  1565. /**
  1566. * Create the groupby part.
  1567. *
  1568. * @param string $groupBy
  1569. * @access public
  1570. * @return object the sql object.
  1571. */
  1572. public function groupBy($groupBy) {
  1573. $this->sql .= ' ' . DAO::GROUPBY . " $groupBy";
  1574. return $this;
  1575. }
  1576. /**
  1577. * Create the having part.
  1578. *
  1579. * @param string $having
  1580. * @access public
  1581. * @return object the sql object.
  1582. */
  1583. public function having($having) {
  1584. $this->sql .= ' ' . DAO::HAVING . " $having";
  1585. return $this;
  1586. }
  1587. /**
  1588. * Get the sql string.
  1589. *
  1590. * @access public
  1591. * @return string
  1592. */
  1593. public function get() {
  1594. return $this->sql;
  1595. }
  1596. /**
  1597. * Uuote a var.
  1598. *
  1599. * @param mixed $value
  1600. * @access public
  1601. * @return mixed
  1602. */
  1603. public function quote($value) {
  1604. // var_dump($value);
  1605. if ($this->magicQuote) {
  1606. $value = stripslashes($value);
  1607. }
  1608. return $this->dbh->quote($value);
  1609. }
  1610. }