dao.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  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. namespace loyalsoft;
  57. use \PDO;
  58. /**
  59. * DAO, data access object.
  60. *
  61. * @package framework
  62. */
  63. class dao {
  64. /* Use these strang strings to avoid conflicting with these keywords in the sql body. */
  65. const WHERE = 'wHeRe';
  66. const GROUPBY = 'gRoUp bY';
  67. const HAVING = 'hAvInG';
  68. const ORDERBY = 'oRdEr bY';
  69. const LIMIT = 'lImiT';
  70. /**
  71. * The global dbh(database handler) object.
  72. *
  73. * @var object
  74. * @access protected
  75. */
  76. protected $dbh;
  77. /**
  78. * The global slaveDBH(database handler) object.
  79. * 从数据库, 主从架构, 主库写如, 从库查询
  80. * @var object
  81. * @access protected
  82. */
  83. protected $slaveDBH;
  84. /**
  85. * The sql object, used to creat the query sql.
  86. *
  87. * @var object
  88. * @access protected
  89. */
  90. public $sqlobj;
  91. /**
  92. * The table of current query.
  93. *
  94. * @var string
  95. * @access public
  96. */
  97. public $table;
  98. /**
  99. * The alias of $this->table.
  100. *
  101. * @var string
  102. * @access public
  103. */
  104. public $alias;
  105. /**
  106. * The fields will be returned.
  107. *
  108. * @var string
  109. * @access public
  110. */
  111. public $fields;
  112. /**
  113. * The query mode, raw or magic.
  114. *
  115. * This var is used to diff dao::from() with sql::from().
  116. *
  117. * @var string
  118. * @access public
  119. */
  120. public $mode;
  121. /**
  122. * The query method: insert, select, update, delete, replace.
  123. *
  124. * @var string
  125. * @access public
  126. */
  127. public $method;
  128. /**
  129. * The sql code of need repair table.
  130. *
  131. * @var string
  132. * @access public
  133. */
  134. public $repairCode = '|1034|1035|1194|1195|1459|';
  135. /**
  136. * The queries executed. Every query will be saved in this array.
  137. *
  138. * @var array
  139. * @access public
  140. */
  141. static public $querys = array();
  142. /**
  143. * The errors.
  144. *
  145. * @var array
  146. * @access public
  147. */
  148. static public $errors = array();
  149. /**
  150. * The construct method.
  151. *
  152. * @access public
  153. * @return void
  154. */
  155. public function __construct() {
  156. }
  157. /**
  158. * Connect to database.
  159. * @param assoc_array $config 配置
  160. * @access public
  161. * @return void
  162. */
  163. public function connectDB($config) {
  164. global $dbh, $slaveDBH;
  165. if (isset($config->paydb->host)) {
  166. $this->dbh = $dbh = $this->connectByPDO($config->paydb);
  167. }
  168. if (isset($config->slaveDB->host)) {
  169. $this->slaveDBH = $slaveDBH = $this->connectByPDO($config->slaveDB);
  170. }
  171. }
  172. /**
  173. * Connect database by PDO.
  174. *
  175. * @param object $params the database params.
  176. * @access private
  177. * @return object|bool
  178. */
  179. private function connectByPDO($params) {
  180. if (!isset($params->driver))
  181. self::triggerError('no pdo driver defined, it should be mysql or sqlite', __FILE__, __LINE__, $exit = true);
  182. if (!isset($params->user))
  183. return false;
  184. if ($params->driver == 'mysql') {
  185. $dsn = "mysql:host={$params->host}; port={$params->port}; dbname={$params->name}";
  186. }
  187. try {
  188. $dbh = new \PDO($dsn, $params->user, $params->password, array(PDO::ATTR_PERSISTENT => $params->persistant));
  189. $dbh->exec("SET NAMES {$params->encoding}");
  190. /* If run on linux, set emulatePrepare and bufferQuery to true. */
  191. if (!isset($params->emulatePrepare) and PHP_OS == 'Linux')
  192. $params->emulatePrepare = true;
  193. if (!isset($params->bufferQuery) and PHP_OS == 'Linux')
  194. $params->bufferQuery = true;
  195. $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
  196. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  197. if (isset($params->strictMode) and $params->strictMode == false)
  198. $dbh->exec("SET @@sql_mode= ''");
  199. if (isset($params->emulatePrepare))
  200. $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, $params->emulatePrepare);
  201. if (isset($params->bufferQuery))
  202. $dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, $params->bufferQuery);
  203. return $dbh;
  204. } catch (PDOException $exception) {
  205. self::triggerError($exception->getMessage(), __FILE__, __LINE__, $exit = true);
  206. }
  207. }
  208. /**
  209. * Set the $table property.
  210. *
  211. * @param string $table
  212. * @access private
  213. * @return void
  214. */
  215. private function setTable($table) {
  216. $this->table = $table;
  217. }
  218. /**
  219. * Set the $alias property.
  220. *
  221. * @param string $alias
  222. * @access private
  223. * @return void
  224. */
  225. private function setAlias($alias) {
  226. $this->alias = $alias;
  227. }
  228. /**
  229. * Set the $fields property.
  230. *
  231. * @param string $fields
  232. * @access private
  233. * @return void
  234. */
  235. private function setFields($fields) {
  236. $this->fields = $fields;
  237. }
  238. /**
  239. * Reset the vars.
  240. *
  241. * @access private
  242. * @return void
  243. */
  244. private function reset() {
  245. $this->setFields('');
  246. $this->setTable('');
  247. $this->setAlias('');
  248. $this->setMode('');
  249. $this->setMethod('');
  250. }
  251. //-------------------- According to the query method, call according method of sql class. --------------------//
  252. /**
  253. * Set the query mode. If the method if like findByxxx, the mode is magic. Else, the mode is raw.
  254. *
  255. * @param string $mode magic|raw
  256. * @access private
  257. * @return void
  258. */
  259. private function setMode($mode = '') {
  260. $this->mode = $mode;
  261. }
  262. /**
  263. * Set the query method: select|update|insert|delete|replace
  264. *
  265. * @param string $method
  266. * @access private
  267. * @return void
  268. */
  269. private function setMethod($method = '') {
  270. $this->method = $method;
  271. }
  272. /**
  273. * The select method, call sql::select().
  274. *
  275. * @param string $fields
  276. * @access public
  277. * @return object the dao object self.
  278. */
  279. public function select($fields = '*') {
  280. $this->setMode('raw');
  281. $this->setMethod('select');
  282. $this->sqlobj = sql::select($fields);
  283. return $this;
  284. }
  285. /**
  286. * The count method, call sql::select() and from().
  287. * use as $this->dao->select()->from(TABLE_BUG)->where()->count();
  288. *
  289. * @access public
  290. * @return void
  291. */
  292. public function count() {
  293. /* Get the SELECT, FROM position, thus get the fields, replace it by count(*). */
  294. // $this->fields
  295. $sql = $this->processSQL();
  296. $sql = str_replace('SELECT', 'SELECT SQL_CALC_FOUND_ROWS ', $sql);
  297. /* Remove the part after order and limit. */
  298. $subLength = strlen($sql);
  299. $orderPOS = strripos($sql, DAO::ORDERBY);
  300. $limitPOS = strripos($sql, DAO::LIMIT);
  301. if ($limitPOS)
  302. $subLength = $limitPOS;
  303. if ($orderPOS)
  304. $subLength = $orderPOS;
  305. $sql = substr($sql, 0, $subLength);
  306. self::$querys[] = $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. */
  731. 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. */
  918. else {
  919. /* Remove the empty items. */
  920. foreach ($replaces as $key => $value)
  921. if (is_null($value))
  922. unset($replaces[$key]);
  923. $replacesCount = count($replaces);
  924. foreach ($error as $errorString) {
  925. if (substr_count($errorString, '%s') == $replacesCount) {
  926. $error = vsprintf($errorString, $replaces);
  927. }
  928. }
  929. }
  930. dao::$errors[$fieldName][] = $error;
  931. }
  932. /**
  933. * Judge any error or not.
  934. *
  935. * @access public
  936. * @return bool
  937. */
  938. public static function isError() {
  939. return !empty(dao::$errors);
  940. }
  941. /**
  942. * Get the errors.
  943. *
  944. * @param boolean $join
  945. * @access public
  946. * @return array
  947. */
  948. public static function getError($join = false) {
  949. $errors = dao::$errors;
  950. dao::$errors = array(); // Must clear it.
  951. if (!$join)
  952. return $errors;
  953. if (is_array($errors)) {
  954. $message = '';
  955. foreach ($errors as $item) {
  956. is_array($item) ? $message .= join('\n', $item) . '\n' : $message .= $item . '\n';
  957. }
  958. return $message;
  959. }
  960. }
  961. /**
  962. * Get the defination of fields of the table.
  963. *
  964. * @access private
  965. * @return array
  966. */
  967. private function getFieldsType() {
  968. try {
  969. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
  970. $sql = "DESC $this->table";
  971. $rawFields = $this->dbh->query($sql)->fetchAll();
  972. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  973. } catch (PDOException $e) {
  974. $this->sqlError($e);
  975. }
  976. foreach ($rawFields as $rawField) {
  977. $firstPOS = strpos($rawField->type, '(');
  978. $type = substr($rawField->type, 0, $firstPOS > 0 ? $firstPOS : strlen($rawField->type));
  979. $type = str_replace(array('big', 'small', 'medium', 'tiny', 'var'), '', $type);
  980. $field = array();
  981. if ($type == 'enum' or $type == 'set') {
  982. $rangeBegin = $firstPOS + 2; // Remove the first quote.
  983. $rangeEnd = strrpos($rawField->type, ')') - 1; // Remove the last quote.
  984. $range = substr($rawField->type, $rangeBegin, $rangeEnd - $rangeBegin);
  985. $field['rule'] = 'reg';
  986. $field['options']['reg'] = '/' . str_replace("','", '|', $range) . '/';
  987. } elseif ($type == 'char') {
  988. $begin = $firstPOS + 1;
  989. $end = strpos($rawField->type, ')', $begin);
  990. $length = substr($rawField->type, $begin, $end - $begin);
  991. $field['rule'] = 'length';
  992. $field['options']['max'] = $length;
  993. $field['options']['min'] = 0;
  994. } elseif ($type == 'int') {
  995. $field['rule'] = 'int';
  996. } elseif ($type == 'float' or $type == 'double') {
  997. $field['rule'] = 'float';
  998. } elseif ($type == 'date') {
  999. $field['rule'] = 'date';
  1000. } else {
  1001. $field['rule'] = 'skip';
  1002. }
  1003. $fields[$rawField->field] = $field;
  1004. }
  1005. return $fields;
  1006. }
  1007. /**
  1008. * Process SQL error by code.
  1009. *
  1010. * @param object $exception
  1011. * @access public
  1012. * @return void
  1013. */
  1014. public function sqlError($exception) {
  1015. $errorInfo = $exception->errorInfo;
  1016. $errorCode = $errorInfo[1];
  1017. $errorMsg = $errorInfo[2];
  1018. $message = $exception->getMessage();
  1019. if (strpos($this->repairCode, "|$errorCode|") !== false #
  1020. or ( $errorCode == '1016' and strpos($errorMsg, 'errno: 145') !== false)) {
  1021. $message .= ' repairTable';
  1022. }
  1023. $sql = $this->sqlobj->get();
  1024. $this->triggerError($message . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
  1025. }
  1026. }
  1027. /**
  1028. * The SQL class.
  1029. *
  1030. * @package framework
  1031. */
  1032. class sql {
  1033. /**
  1034. * The max count of params of all methods.
  1035. *
  1036. */
  1037. const MAX_ARGS = 3;
  1038. /**
  1039. * The sql string.
  1040. *
  1041. * @var string
  1042. * @access public
  1043. */
  1044. public $sql = '';
  1045. /**
  1046. * The global $dbh.
  1047. *
  1048. *
  1049. * @access protected
  1050. */
  1051. protected $dbh;
  1052. /**
  1053. * The data to update or insert.
  1054. *
  1055. * @var mix
  1056. * @access protected
  1057. */
  1058. public $data;
  1059. /**
  1060. * Is the first time to call set.
  1061. *
  1062. * @var bool
  1063. * @access private;
  1064. */
  1065. private $isFirstSet = true;
  1066. /**
  1067. * If in the logic of judge condition or not.
  1068. *
  1069. * @var bool
  1070. * @access private;
  1071. */
  1072. private $inCondition = false;
  1073. /**
  1074. * The condition is true or not.
  1075. *
  1076. * @var bool
  1077. * @access private;
  1078. */
  1079. private $conditionIsTrue = false;
  1080. /**
  1081. * Magic quote or not.
  1082. *
  1083. * @var bool
  1084. * @access public
  1085. */
  1086. public $magicQuote;
  1087. /**
  1088. * The construct function. user factory() to instance it.
  1089. *
  1090. * @param string $table
  1091. * @access private
  1092. * @return void
  1093. */
  1094. private function __construct($table = '') {
  1095. global $dbh;
  1096. $this->dbh = $dbh;
  1097. $this->magicQuote = get_magic_quotes_gpc();
  1098. }
  1099. /**
  1100. * The factory method.
  1101. *
  1102. * @param string $table
  1103. * @access public
  1104. * @return object the sql object.
  1105. */
  1106. public static function factory($table = '') {
  1107. return new sql($table);
  1108. }
  1109. /**
  1110. * The sql is select.
  1111. *
  1112. * @param string $field
  1113. * @access public
  1114. * @return object the sql object.
  1115. */
  1116. public static function select($field = '*') {
  1117. $sqlobj = self::factory();
  1118. $sqlobj->sql = "SELECT $field ";
  1119. return $sqlobj;
  1120. }
  1121. /**
  1122. * The sql is update.
  1123. *
  1124. * @param string $table
  1125. * @access public
  1126. * @return object the sql object.
  1127. */
  1128. public static function update($table) {
  1129. $sqlobj = self::factory();
  1130. $sqlobj->sql = "UPDATE $table SET ";
  1131. return $sqlobj;
  1132. }
  1133. /**
  1134. * The sql is insert.
  1135. *
  1136. * @param string $table
  1137. * @access public
  1138. * @return object the sql object.
  1139. */
  1140. public static function insert($table) {
  1141. $sqlobj = self::factory();
  1142. $sqlobj->sql = "INSERT INTO $table SET ";
  1143. return $sqlobj;
  1144. }
  1145. /**
  1146. * The sql is replace.
  1147. *
  1148. * @param string $table
  1149. * @access public
  1150. * @return object the sql object.
  1151. */
  1152. public static function replace($table) {
  1153. $sqlobj = self::factory();
  1154. $sqlobj->sql = "REPLACE $table SET ";
  1155. return $sqlobj;
  1156. }
  1157. /**
  1158. * The sql is delete.
  1159. *
  1160. * @access public
  1161. * @return object the sql object.
  1162. */
  1163. public static function delete() {
  1164. $sqlobj = self::factory();
  1165. $sqlobj->sql = "DELETE ";
  1166. return $sqlobj;
  1167. }
  1168. /**
  1169. * Join the data items by key = value.
  1170. *
  1171. * @param object $data
  1172. * @access public
  1173. * @return object the sql object.
  1174. */
  1175. public function data($data) {
  1176. $data = (object) $data;
  1177. foreach ($data as $field => $value) {
  1178. if (!preg_match('|^\w+$|', $field)) {
  1179. unset($data->$field);
  1180. continue;
  1181. }
  1182. $this->sql .= "`$field` = " . $this->quote($value) . ',';
  1183. }
  1184. $this->data = $data;
  1185. $this->sql = rtrim($this->sql, ','); // Remove the last ','.
  1186. return $this;
  1187. }
  1188. /**
  1189. * Aadd an '(' at left.
  1190. *
  1191. * @param int $count
  1192. * @access public
  1193. * @return ojbect the sql object.
  1194. */
  1195. public function markLeft($count = 1) {
  1196. $this->sql .= str_repeat('(', $count);
  1197. return $this;
  1198. }
  1199. /**
  1200. * Add an ')' ad right.
  1201. *
  1202. * @param int $count
  1203. * @access public
  1204. * @return object the sql object.
  1205. */
  1206. public function markRight($count = 1) {
  1207. $this->sql .= str_repeat(')', $count);
  1208. return $this;
  1209. }
  1210. /**
  1211. * The set part.
  1212. *
  1213. * @param string $set
  1214. * @access public
  1215. * @return object the sql object.
  1216. */
  1217. public function set($set) {
  1218. if ($this->isFirstSet) {
  1219. $this->sql .= " $set ";
  1220. $this->isFirstSet = false;
  1221. } else {
  1222. $this->sql .= ", $set";
  1223. }
  1224. return $this;
  1225. }
  1226. /**
  1227. * Create the from part.
  1228. *
  1229. * @param string $table
  1230. * @access public
  1231. * @return object the sql object.
  1232. */
  1233. public function from($table) {
  1234. $this->sql .= "FROM $table";
  1235. return $this;
  1236. }
  1237. /**
  1238. * Create the Alias part.
  1239. *
  1240. * @param string $alias
  1241. * @access public
  1242. * @return object the sql object.
  1243. */
  1244. public function alias($alias) {
  1245. $this->sql .= " AS $alias ";
  1246. return $this;
  1247. }
  1248. /**
  1249. * Create the left join part.
  1250. *
  1251. * @param string $table
  1252. * @access public
  1253. * @return object the sql object.
  1254. */
  1255. public function leftJoin($table) {
  1256. $this->sql .= " LEFT JOIN $table";
  1257. return $this;
  1258. }
  1259. /**
  1260. * Create the on part.
  1261. *
  1262. * @param string $condition
  1263. * @access public
  1264. * @return object the sql object.
  1265. */
  1266. public function on($condition) {
  1267. $this->sql .= " ON $condition ";
  1268. return $this;
  1269. }
  1270. /**
  1271. * Begin condition judge.
  1272. *
  1273. * @param bool $condition
  1274. * @access public
  1275. * @return object the sql object.
  1276. */
  1277. public function beginIF($condition) {
  1278. $this->inCondition = true;
  1279. $this->conditionIsTrue = $condition;
  1280. return $this;
  1281. }
  1282. /**
  1283. * End the condition judge.
  1284. *
  1285. * @access public
  1286. * @return object the sql object.
  1287. */
  1288. public function fi() {
  1289. $this->inCondition = false;
  1290. $this->conditionIsTrue = false;
  1291. return $this;
  1292. }
  1293. /**
  1294. * Create the where part.
  1295. *
  1296. * @param string $arg1 the field name
  1297. * @param string $arg2 the operator
  1298. * @param string $arg3 the value
  1299. * @access public
  1300. * @return object the sql object.
  1301. */
  1302. public function where($arg1, $arg2 = null, $arg3 = null) {
  1303. if ($this->inCondition and ! $this->conditionIsTrue)
  1304. return $this;
  1305. if ($arg3 !== null) {
  1306. $value = $this->quote($arg3);
  1307. $condition = "`$arg1` $arg2 " . $this->quote($arg3);
  1308. } else {
  1309. $condition = $arg1;
  1310. }
  1311. $this->sql .= ' ' . DAO::WHERE . " $condition ";
  1312. return $this;
  1313. }
  1314. /**
  1315. * Create the AND part.
  1316. *
  1317. * @param string $condition
  1318. * @access public
  1319. * @return object the sql object.
  1320. */
  1321. public function andWhere($condition) {
  1322. if ($this->inCondition and ! $this->conditionIsTrue)
  1323. return $this;
  1324. $this->sql .= " AND $condition ";
  1325. return $this;
  1326. }
  1327. /**
  1328. * Create the OR part.
  1329. *
  1330. * @param bool $condition
  1331. * @access public
  1332. * @return object the sql object.
  1333. */
  1334. public function orWhere($condition) {
  1335. if ($this->inCondition and ! $this->conditionIsTrue)
  1336. return $this;
  1337. $this->sql .= " OR $condition ";
  1338. return $this;
  1339. }
  1340. /**
  1341. * Create the '='.
  1342. *
  1343. * @param string $value
  1344. * @access public
  1345. * @return object the sql object.
  1346. */
  1347. public function eq($value) {
  1348. if ($this->inCondition and ! $this->conditionIsTrue)
  1349. return $this;
  1350. $this->sql .= " = " . $this->quote($value);
  1351. return $this;
  1352. }
  1353. /**
  1354. * Create '!='.
  1355. *
  1356. * @param string $value
  1357. * @access public
  1358. * @return void the sql object.
  1359. */
  1360. public function ne($value) {
  1361. if ($this->inCondition and ! $this->conditionIsTrue)
  1362. return $this;
  1363. $this->sql .= " != " . $this->quote($value);
  1364. return $this;
  1365. }
  1366. /**
  1367. * Create '>'.
  1368. *
  1369. * @param string $value
  1370. * @access public
  1371. * @return object the sql object.
  1372. */
  1373. public function gt($value) {
  1374. if ($this->inCondition and ! $this->conditionIsTrue)
  1375. return $this;
  1376. $this->sql .= " > " . $this->quote($value);
  1377. return $this;
  1378. }
  1379. /**
  1380. * Create '>='.
  1381. *
  1382. * @param string $value
  1383. * @access public
  1384. * @return object the sql object.
  1385. */
  1386. public function ge($value) {
  1387. if ($this->inCondition and ! $this->conditionIsTrue)
  1388. return $this;
  1389. $this->sql .= " >= " . $this->quote($value);
  1390. return $this;
  1391. }
  1392. /**
  1393. * Create '<'.
  1394. *
  1395. * @param mixed $value
  1396. * @access public
  1397. * @return object the sql object.
  1398. */
  1399. public function lt($value) {
  1400. if ($this->inCondition and ! $this->conditionIsTrue)
  1401. return $this;
  1402. $this->sql .= " < " . $this->quote($value);
  1403. return $this;
  1404. }
  1405. /**
  1406. * Create '<='.
  1407. *
  1408. * @param mixed $value
  1409. * @access public
  1410. * @return object the sql object.
  1411. */
  1412. public function le($value) {
  1413. if ($this->inCondition && !$this->conditionIsTrue) {
  1414. return $this;
  1415. }
  1416. $this->sql .= " <= " . $this->quote($value);
  1417. return $this;
  1418. }
  1419. /**
  1420. * Create "between and"
  1421. *
  1422. * @param string $min
  1423. * @param string $max
  1424. * @access public
  1425. * @return object the sql object.
  1426. */
  1427. public function between($min, $max) {
  1428. if ($this->inCondition and ! $this->conditionIsTrue)
  1429. return $this;
  1430. $min = $this->quote($min);
  1431. $max = $this->quote($max);
  1432. $this->sql .= " BETWEEN $min AND $max ";
  1433. return $this;
  1434. }
  1435. /**
  1436. * Create in part.
  1437. *
  1438. * @param string|array $ids list string by ',' or an array
  1439. * @access public
  1440. * @return object the sql object.
  1441. */
  1442. public function in($ids) {
  1443. // var_dump($ids);
  1444. if ($this->inCondition and ! $this->conditionIsTrue)
  1445. return $this;
  1446. $this->sql .= self::dbIN($ids);
  1447. return $this;
  1448. }
  1449. /**
  1450. * Create the in('a', 'b') string.
  1451. *
  1452. * @param string|array $ids the id lists, can be a array or a string with ids joined with comma.
  1453. * @static
  1454. * @access public
  1455. * @return string the string like IN('a', 'b').
  1456. */
  1457. private static function dbIN($ids) {
  1458. if (is_array($ids))
  1459. return "IN ('" . join("','", $ids) . "')";
  1460. return "IN ('" . str_replace(',', "','", str_replace(' ', '', $ids)) . "')";
  1461. }
  1462. /**
  1463. * Create not in part.
  1464. *
  1465. * @param string|array $ids list string by ',' or an array
  1466. * @access public
  1467. * @return object the sql object.
  1468. */
  1469. public function notin($ids) {
  1470. if ($this->inCondition and ! $this->conditionIsTrue)
  1471. return $this;
  1472. $this->sql .= ' NOT ' . self::dbIN($ids);
  1473. return $this;
  1474. }
  1475. /**
  1476. * Create the like by part.
  1477. *
  1478. * @param string $string
  1479. * @access public
  1480. * @return object the sql object.
  1481. */
  1482. public function like($string) {
  1483. if ($this->inCondition and ! $this->conditionIsTrue)
  1484. return $this;
  1485. $this->sql .= " LIKE " . $this->quote($string);
  1486. return $this;
  1487. }
  1488. /**
  1489. * Create the not like by part.
  1490. *
  1491. * @param string $string
  1492. * @access public
  1493. * @return object the sql object.
  1494. */
  1495. public function notLike($string) {
  1496. if ($this->inCondition and ! $this->conditionIsTrue)
  1497. return $this;
  1498. $this->sql .= "NOT LIKE " . $this->quote($string);
  1499. return $this;
  1500. }
  1501. /**
  1502. * Create the find_in_set by part.
  1503. *
  1504. * @param int $str
  1505. * @param int $strList
  1506. * @access public
  1507. * @return object the sql object.
  1508. */
  1509. public function findInSet($str, $strList) {
  1510. if ($this->inCondition and ! $this->conditionIsTrue)
  1511. return $this;
  1512. $this->sql .= "FIND_IN_SET(" . $str . "," . $strList . ")";
  1513. }
  1514. /**
  1515. * Create the order by part.
  1516. *
  1517. * @param string $order
  1518. * @access public
  1519. * @return object the sql object.
  1520. */
  1521. public function orderBy($order) {
  1522. if ($this->inCondition and ! $this->conditionIsTrue)
  1523. return $this;
  1524. $order = str_replace(array('|', '', '_'), ' ', $order);
  1525. /* Add "`" in order string. */
  1526. /* When order has limit string. */
  1527. $pos = stripos($order, 'limit');
  1528. $orders = $pos ? substr($order, 0, $pos) : $order;
  1529. $limit = $pos ? substr($order, $pos) : '';
  1530. $orders = explode(',', $orders);
  1531. foreach ($orders as $i => $order) {
  1532. $orderParse = explode(' ', trim($order));
  1533. foreach ($orderParse as $key => $value) {
  1534. $value = trim($value);
  1535. if (empty($value) or strtolower($value) == 'desc' or strtolower($value) == 'asc')
  1536. continue;
  1537. $field = trim($value, '`');
  1538. /* such as t1.id field. */
  1539. if (strpos($value, '.') !== false)
  1540. list($table, $field) = explode('.', $field);
  1541. $field = "`$field`";
  1542. $orderParse[$key] = isset($table) ? $table . '.' . $field : $field;
  1543. unset($table);
  1544. }
  1545. $orders[$i] = join(' ', $orderParse);
  1546. }
  1547. $order = join(',', $orders) . ' ' . $limit;
  1548. $this->sql .= ' ' . DAO::ORDERBY . " $order";
  1549. return $this;
  1550. }
  1551. /**
  1552. * Create the limit part.
  1553. *
  1554. * @param string $limit
  1555. * @access public
  1556. * @return object the sql object.
  1557. */
  1558. public function limit($limit) {
  1559. if (empty($limit))
  1560. return $this;
  1561. stripos($limit, 'limit') !== false ? $this->sql .= " $limit " : $this->sql .= ' ' . DAO::LIMIT . " $limit ";
  1562. return $this;
  1563. }
  1564. /**
  1565. * Create the groupby part.
  1566. *
  1567. * @param string $groupBy
  1568. * @access public
  1569. * @return object the sql object.
  1570. */
  1571. public function groupBy($groupBy) {
  1572. $this->sql .= ' ' . DAO::GROUPBY . " $groupBy";
  1573. return $this;
  1574. }
  1575. /**
  1576. * Create the having part.
  1577. *
  1578. * @param string $having
  1579. * @access public
  1580. * @return object the sql object.
  1581. */
  1582. public function having($having) {
  1583. $this->sql .= ' ' . DAO::HAVING . " $having";
  1584. return $this;
  1585. }
  1586. /**
  1587. * Get the sql string.
  1588. *
  1589. * @access public
  1590. * @return string
  1591. */
  1592. public function get() {
  1593. return $this->sql;
  1594. }
  1595. /**
  1596. * Uuote a var.
  1597. *
  1598. * @param mixed $value
  1599. * @access public
  1600. * @return mixed
  1601. */
  1602. public function quote($value) {
  1603. if ($this->magicQuote)
  1604. $value = stripslashes($value);
  1605. return $this->dbh->quote($value);
  1606. }
  1607. }