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. */ else {
  731. /* Create the max counts of sql class methods, and then create $arg0, $arg1... */
  732. for ($i = 0; $i < SQL::MAX_ARGS; $i++) {
  733. ${"arg$i"} = isset($funcArgs[$i]) ? $funcArgs[$i] : null;
  734. }
  735. $this->sqlobj->$funcName($arg0, $arg1, $arg2);
  736. return $this;
  737. }
  738. }
  739. //-------------------- Checking.--------------------//
  740. /**
  741. * Check a filed is satisfied with the check rule.
  742. *
  743. * @param string $fieldName the field to check
  744. * @param string $funcName the check rule
  745. * @access public
  746. * @return object the dao object self.
  747. */
  748. public function check($fieldName, $funcName) {
  749. /* If no this field in the data, reuturn. */
  750. if (!isset($this->sqlobj->data->$fieldName))
  751. return $this;
  752. /* Set the field label and value. */
  753. global $lang, $config, $app;
  754. $table = strtolower(str_replace(array($config->db->prefix, '`'), '', $this->table));
  755. $fieldLabel = isset($lang->$table->$fieldName) ? $lang->$table->$fieldName : $fieldName;
  756. $value = $this->sqlobj->data->$fieldName;
  757. /* Check unique. */
  758. if ($funcName == 'unique') {
  759. $args = func_get_args();
  760. $sql = "SELECT COUNT(*) AS count FROM $this->table WHERE `$fieldName` = " . $this->sqlobj->quote($value);
  761. if (isset($args[2]))
  762. $sql .= ' AND ' . $args[2];
  763. try {
  764. $row = $this->dbh->query($sql)->fetch();
  765. if ($row->count != 0)
  766. $this->logError($funcName, $fieldName, $fieldLabel, array($value));
  767. } catch (PDOException $e) {
  768. $this->sqlError($e);
  769. }
  770. } else {
  771. /* Create the params. */
  772. $funcArgs = func_get_args();
  773. unset($funcArgs[0]);
  774. unset($funcArgs[1]);
  775. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  776. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  777. }
  778. $checkFunc = 'check' . $funcName;
  779. if (validater::$checkFunc($value, $arg0, $arg1, $arg2) === false) {
  780. $this->logError($funcName, $fieldName, $fieldLabel, $funcArgs);
  781. }
  782. }
  783. return $this;
  784. }
  785. /**
  786. * Check a field, if satisfied with the condition.
  787. *
  788. * @param string $condition
  789. * @param string $fieldName
  790. * @param string $funcName
  791. * @access public
  792. * @return object the dao object self.
  793. */
  794. public function checkIF($condition, $fieldName, $funcName) {
  795. if (!$condition)
  796. return $this;
  797. $funcArgs = func_get_args();
  798. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  799. ${"arg$i"} = isset($funcArgs[$i + 3]) ? $funcArgs[$i + 3] : null;
  800. }
  801. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  802. return $this;
  803. }
  804. /**
  805. * Batch check some fileds.
  806. *
  807. * @param string $fields the fields to check, join with ,
  808. * @param string $funcName
  809. * @access public
  810. * @return object the dao object self.
  811. */
  812. public function batchCheck($fields, $funcName) {
  813. $fields = explode(',', str_replace(' ', '', $fields));
  814. $funcArgs = func_get_args();
  815. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  816. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  817. }
  818. foreach ($fields as $fieldName)
  819. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  820. return $this;
  821. }
  822. /**
  823. * Batch check fields on the condition is true.
  824. *
  825. * @param string $condition
  826. * @param string $fields
  827. * @param string $funcName
  828. * @access public
  829. * @return object the dao object self.
  830. */
  831. public function batchCheckIF($condition, $fields, $funcName) {
  832. if (!$condition)
  833. return $this;
  834. $fields = explode(',', str_replace(' ', '', $fields));
  835. $funcArgs = func_get_args();
  836. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  837. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  838. }
  839. foreach ($fields as $fieldName)
  840. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  841. return $this;
  842. }
  843. /**
  844. * Check the fields according the the database schema.
  845. *
  846. * @param string $skipFields fields to skip checking
  847. * @access public
  848. * @return object the dao object self.
  849. */
  850. public function autoCheck($skipFields = '') {
  851. $fields = $this->getFieldsType();
  852. $skipFields = ",$skipFields,";
  853. foreach ($fields as $fieldName => $validater) {
  854. if (strpos($skipFields, $fieldName) !== false)
  855. continue; // skip it.
  856. if (!isset($this->sqlobj->data->$fieldName))
  857. continue;
  858. if ($validater['rule'] == 'skip')
  859. continue;
  860. $options = array();
  861. if (isset($validater['options']))
  862. $options = array_values($validater['options']);
  863. for ($i = 0; $i < VALIDATER::MAX_ARGS; $i++) {
  864. ${"arg$i"} = isset($options[$i]) ? $options[$i] : null;
  865. }
  866. $this->check($fieldName, $validater['rule'], $arg0, $arg1, $arg2);
  867. }
  868. return $this;
  869. }
  870. /**
  871. * 检查表是否存在
  872. * @param type $tableName
  873. * @return type
  874. */
  875. public function tableExist($tableName) {
  876. $this->reset();
  877. $this->setMethod('select');
  878. $sql = "SELECT 1 FROM $tableName LIMIT 1";
  879. try {
  880. if ($this->slaveDBH and $this->method == 'select') {
  881. $ret = $this->slaveDBH->query($sql)->fetch();
  882. } else {
  883. $ret = $this->dbh->query($sql)->fetch();
  884. }
  885. } catch (Exception $exc) {
  886. return false;
  887. }
  888. // Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
  889. return $ret !== FALSE; # false代表表不存在
  890. }
  891. /**
  892. * Log the error.
  893. *
  894. * For the error notice, see module/common/lang.
  895. *
  896. * @param string $checkType the check rule
  897. * @param string $fieldName the field name
  898. * @param string $fieldLabel the field label
  899. * @param array $funcArgs the args
  900. * @access public
  901. * @return void
  902. */
  903. public function logError($checkType, $fieldName, $fieldLabel, $funcArgs = array()) {
  904. global $lang;
  905. $error = $lang->error->$checkType;
  906. $replaces = array_merge(array($fieldLabel), $funcArgs); // the replace values.
  907. /* Just a string, cycle the $replaces. */
  908. if (!is_array($error)) {
  909. foreach ($replaces as $replace) {
  910. $pos = strpos($error, '%s');
  911. if ($pos === false)
  912. break;
  913. $error = substr($error, 0, $pos) . $replace . substr($error, $pos + 2);
  914. }
  915. }
  916. /* If the error define is an array, select the one which %s counts match the $replaces. */ else {
  917. /* Remove the empty items. */
  918. foreach ($replaces as $key => $value)
  919. if (is_null($value))
  920. unset($replaces[$key]);
  921. $replacesCount = count($replaces);
  922. foreach ($error as $errorString) {
  923. if (substr_count($errorString, '%s') == $replacesCount) {
  924. $error = vsprintf($errorString, $replaces);
  925. }
  926. }
  927. }
  928. dao::$errors[$fieldName][] = $error;
  929. }
  930. /**
  931. * Judge any error or not.
  932. *
  933. * @access public
  934. * @return bool
  935. */
  936. public static function isError() {
  937. return !empty(dao::$errors);
  938. }
  939. /**
  940. * Get the errors.
  941. *
  942. * @param boolean $join
  943. * @access public
  944. * @return array
  945. */
  946. public static function getError($join = false) {
  947. $errors = dao::$errors;
  948. dao::$errors = array(); // Must clear it.
  949. if (!$join)
  950. return $errors;
  951. if (is_array($errors)) {
  952. $message = '';
  953. foreach ($errors as $item) {
  954. is_array($item) ? $message .= join('\n', $item) . '\n' : $message .= $item . '\n';
  955. }
  956. return $message;
  957. }
  958. }
  959. /**
  960. * Get the defination of fields of the table.
  961. *
  962. * @access private
  963. * @return array
  964. */
  965. private function getFieldsType() {
  966. try {
  967. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
  968. $sql = "DESC $this->table";
  969. $rawFields = $this->dbh->query($sql)->fetchAll();
  970. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  971. } catch (PDOException $e) {
  972. $this->sqlError($e);
  973. }
  974. foreach ($rawFields as $rawField) {
  975. $firstPOS = strpos($rawField->type, '(');
  976. $type = substr($rawField->type, 0, $firstPOS > 0 ? $firstPOS : strlen($rawField->type));
  977. $type = str_replace(array('big', 'small', 'medium', 'tiny', 'var'), '', $type);
  978. $field = array();
  979. if ($type == 'enum' or $type == 'set') {
  980. $rangeBegin = $firstPOS + 2; // Remove the first quote.
  981. $rangeEnd = strrpos($rawField->type, ')') - 1; // Remove the last quote.
  982. $range = substr($rawField->type, $rangeBegin, $rangeEnd - $rangeBegin);
  983. $field['rule'] = 'reg';
  984. $field['options']['reg'] = '/' . str_replace("','", '|', $range) . '/';
  985. } elseif ($type == 'char') {
  986. $begin = $firstPOS + 1;
  987. $end = strpos($rawField->type, ')', $begin);
  988. $length = substr($rawField->type, $begin, $end - $begin);
  989. $field['rule'] = 'length';
  990. $field['options']['max'] = $length;
  991. $field['options']['min'] = 0;
  992. } elseif ($type == 'int') {
  993. $field['rule'] = 'int';
  994. } elseif ($type == 'float' or $type == 'double') {
  995. $field['rule'] = 'float';
  996. } elseif ($type == 'date') {
  997. $field['rule'] = 'date';
  998. } else {
  999. $field['rule'] = 'skip';
  1000. }
  1001. $fields[$rawField->field] = $field;
  1002. }
  1003. return $fields;
  1004. }
  1005. /**
  1006. * Process SQL error by code.
  1007. *
  1008. * @param object $exception
  1009. * @access public
  1010. * @return void
  1011. */
  1012. public function sqlError($exception) {
  1013. $errorInfo = $exception->errorInfo;
  1014. $errorCode = $errorInfo[1];
  1015. $errorMsg = $errorInfo[2];
  1016. $message = $exception->getMessage();
  1017. if (strpos($this->repairCode, "|$errorCode|") !== false #
  1018. or ( $errorCode == '1016' and strpos($errorMsg, 'errno: 145') !== false)) {
  1019. $message .= ' repairTable';
  1020. }
  1021. $sql = $this->sqlobj->get();
  1022. $this->triggerError($message . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
  1023. }
  1024. }
  1025. /**
  1026. * The SQL class.
  1027. *
  1028. * @package framework
  1029. */
  1030. class sql {
  1031. /**
  1032. * The max count of params of all methods.
  1033. *
  1034. */
  1035. const MAX_ARGS = 3;
  1036. /**
  1037. * The sql string.
  1038. *
  1039. * @var string
  1040. * @access public
  1041. */
  1042. public $sql = '';
  1043. /**
  1044. * The global $dbh.
  1045. *
  1046. *
  1047. * @access protected
  1048. */
  1049. protected $dbh;
  1050. /**
  1051. * The data to update or insert.
  1052. *
  1053. * @var mix
  1054. * @access protected
  1055. */
  1056. public $data;
  1057. /**
  1058. * Is the first time to call set.
  1059. *
  1060. * @var bool
  1061. * @access private;
  1062. */
  1063. private $isFirstSet = true;
  1064. /**
  1065. * If in the logic of judge condition or not.
  1066. *
  1067. * @var bool
  1068. * @access private;
  1069. */
  1070. private $inCondition = false;
  1071. /**
  1072. * The condition is true or not.
  1073. *
  1074. * @var bool
  1075. * @access private;
  1076. */
  1077. private $conditionIsTrue = false;
  1078. /**
  1079. * Magic quote or not.
  1080. *
  1081. * @var bool
  1082. * @access public
  1083. */
  1084. public $magicQuote;
  1085. /**
  1086. * The construct function. user factory() to instance it.
  1087. *
  1088. * @param string $table
  1089. * @access private
  1090. * @return void
  1091. */
  1092. private function __construct($table = '') {
  1093. global $dbh;
  1094. $this->dbh = $dbh;
  1095. $this->magicQuote = false; // get_magic_quotes_gpc();
  1096. }
  1097. /**
  1098. * The factory method.
  1099. *
  1100. * @param string $table
  1101. * @access public
  1102. * @return object the sql object.
  1103. */
  1104. public static function factory($table = '') {
  1105. return new sql($table);
  1106. }
  1107. /**
  1108. * The sql is select.
  1109. *
  1110. * @param string $field
  1111. * @access public
  1112. * @return object the sql object.
  1113. */
  1114. public static function select($field = '*') {
  1115. $sqlobj = self::factory();
  1116. $sqlobj->sql = "SELECT $field ";
  1117. return $sqlobj;
  1118. }
  1119. /**
  1120. * The sql is update.
  1121. *
  1122. * @param string $table
  1123. * @access public
  1124. * @return object the sql object.
  1125. */
  1126. public static function update($table) {
  1127. $sqlobj = self::factory();
  1128. $sqlobj->sql = "UPDATE $table SET ";
  1129. return $sqlobj;
  1130. }
  1131. /**
  1132. * The sql is insert.
  1133. *
  1134. * @param string $table
  1135. * @access public
  1136. * @return object the sql object.
  1137. */
  1138. public static function insert($table) {
  1139. $sqlobj = self::factory();
  1140. $sqlobj->sql = "INSERT INTO $table SET ";
  1141. return $sqlobj;
  1142. }
  1143. /**
  1144. * The sql is replace.
  1145. *
  1146. * @param string $table
  1147. * @access public
  1148. * @return object the sql object.
  1149. */
  1150. public static function replace($table) {
  1151. $sqlobj = self::factory();
  1152. $sqlobj->sql = "REPLACE $table SET ";
  1153. return $sqlobj;
  1154. }
  1155. /**
  1156. * The sql is delete.
  1157. *
  1158. * @access public
  1159. * @return object the sql object.
  1160. */
  1161. public static function delete() {
  1162. $sqlobj = self::factory();
  1163. $sqlobj->sql = "DELETE ";
  1164. return $sqlobj;
  1165. }
  1166. /**
  1167. * Join the data items by key = value.
  1168. *
  1169. * @param object $data
  1170. * @access public
  1171. * @return object the sql object.
  1172. */
  1173. public function data($data) {
  1174. $data = (object) $data;
  1175. foreach ($data as $field => $value) {
  1176. if (!preg_match('|^\w+$|', $field)) {
  1177. unset($data->$field);
  1178. continue;
  1179. }
  1180. $this->sql .= "`$field` = " . $this->quote($value) . ',';
  1181. }
  1182. $this->data = $data;
  1183. $this->sql = rtrim($this->sql, ','); // Remove the last ','.
  1184. return $this;
  1185. }
  1186. /**
  1187. * Aadd an '(' at left.
  1188. *
  1189. * @param int $count
  1190. * @access public
  1191. * @return ojbect the sql object.
  1192. */
  1193. public function markLeft($count = 1) {
  1194. $this->sql .= str_repeat('(', $count);
  1195. return $this;
  1196. }
  1197. /**
  1198. * Add an ')' ad right.
  1199. *
  1200. * @param int $count
  1201. * @access public
  1202. * @return object the sql object.
  1203. */
  1204. public function markRight($count = 1) {
  1205. $this->sql .= str_repeat(')', $count);
  1206. return $this;
  1207. }
  1208. /**
  1209. * The set part.
  1210. *
  1211. * @param string $set
  1212. * @access public
  1213. * @return object the sql object.
  1214. */
  1215. public function set($set) {
  1216. if ($this->isFirstSet) {
  1217. $this->sql .= " $set ";
  1218. $this->isFirstSet = false;
  1219. } else {
  1220. $this->sql .= ", $set";
  1221. }
  1222. return $this;
  1223. }
  1224. /**
  1225. * Create the from part.
  1226. *
  1227. * @param string $table
  1228. * @access public
  1229. * @return object the sql object.
  1230. */
  1231. public function from($table) {
  1232. $this->sql .= "FROM $table";
  1233. return $this;
  1234. }
  1235. /**
  1236. * Create the Alias part.
  1237. *
  1238. * @param string $alias
  1239. * @access public
  1240. * @return object the sql object.
  1241. */
  1242. public function alias($alias) {
  1243. $this->sql .= " AS $alias ";
  1244. return $this;
  1245. }
  1246. /**
  1247. * Create the left join part.
  1248. *
  1249. * @param string $table
  1250. * @access public
  1251. * @return object the sql object.
  1252. */
  1253. public function leftJoin($table) {
  1254. $this->sql .= " LEFT JOIN $table";
  1255. return $this;
  1256. }
  1257. /**
  1258. * Create the on part.
  1259. *
  1260. * @param string $condition
  1261. * @access public
  1262. * @return object the sql object.
  1263. */
  1264. public function on($condition) {
  1265. $this->sql .= " ON $condition ";
  1266. return $this;
  1267. }
  1268. /**
  1269. * Begin condition judge.
  1270. *
  1271. * @param bool $condition
  1272. * @access public
  1273. * @return object the sql object.
  1274. */
  1275. public function beginIF($condition) {
  1276. $this->inCondition = true;
  1277. $this->conditionIsTrue = $condition;
  1278. return $this;
  1279. }
  1280. /**
  1281. * End the condition judge.
  1282. *
  1283. * @access public
  1284. * @return object the sql object.
  1285. */
  1286. public function fi() {
  1287. $this->inCondition = false;
  1288. $this->conditionIsTrue = false;
  1289. return $this;
  1290. }
  1291. /**
  1292. * Create the where part.
  1293. *
  1294. * @param string $arg1 the field name
  1295. * @param string $arg2 the operator
  1296. * @param string $arg3 the value
  1297. * @access public
  1298. * @return object the sql object.
  1299. */
  1300. public function where($arg1, $arg2 = null, $arg3 = null) {
  1301. if ($this->inCondition and!$this->conditionIsTrue)
  1302. return $this;
  1303. if ($arg3 !== null) {
  1304. $value = $this->quote($arg3);
  1305. $condition = "`$arg1` $arg2 " . $this->quote($arg3);
  1306. } else {
  1307. $condition = $arg1;
  1308. }
  1309. $this->sql .= ' ' . DAO::WHERE . " $condition ";
  1310. return $this;
  1311. }
  1312. /**
  1313. * Create the AND part.
  1314. *
  1315. * @param string $condition
  1316. * @access public
  1317. * @return object the sql object.
  1318. */
  1319. public function andWhere($condition) {
  1320. if ($this->inCondition and!$this->conditionIsTrue)
  1321. return $this;
  1322. $this->sql .= " AND $condition ";
  1323. return $this;
  1324. }
  1325. /**
  1326. * Create the OR part.
  1327. *
  1328. * @param bool $condition
  1329. * @access public
  1330. * @return object the sql object.
  1331. */
  1332. public function orWhere($condition) {
  1333. if ($this->inCondition and!$this->conditionIsTrue)
  1334. return $this;
  1335. $this->sql .= " OR $condition ";
  1336. return $this;
  1337. }
  1338. /**
  1339. * Create the '='.
  1340. *
  1341. * @param string $value
  1342. * @access public
  1343. * @return object the sql object.
  1344. */
  1345. public function eq($value) {
  1346. if ($this->inCondition and!$this->conditionIsTrue)
  1347. return $this;
  1348. $this->sql .= " = " . $this->quote($value);
  1349. return $this;
  1350. }
  1351. /**
  1352. * Create '!='.
  1353. *
  1354. * @param string $value
  1355. * @access public
  1356. * @return void the sql object.
  1357. */
  1358. public function ne($value) {
  1359. if ($this->inCondition and!$this->conditionIsTrue)
  1360. return $this;
  1361. $this->sql .= " != " . $this->quote($value);
  1362. return $this;
  1363. }
  1364. /**
  1365. * Create '>'.
  1366. *
  1367. * @param string $value
  1368. * @access public
  1369. * @return object the sql object.
  1370. */
  1371. public function gt($value) {
  1372. if ($this->inCondition and!$this->conditionIsTrue)
  1373. return $this;
  1374. $this->sql .= " > " . $this->quote($value);
  1375. return $this;
  1376. }
  1377. /**
  1378. * Create '>='.
  1379. *
  1380. * @param string $value
  1381. * @access public
  1382. * @return object the sql object.
  1383. */
  1384. public function ge($value) {
  1385. if ($this->inCondition and!$this->conditionIsTrue)
  1386. return $this;
  1387. $this->sql .= " >= " . $this->quote($value);
  1388. return $this;
  1389. }
  1390. /**
  1391. * Create '<'.
  1392. *
  1393. * @param mixed $value
  1394. * @access public
  1395. * @return object the sql object.
  1396. */
  1397. public function lt($value) {
  1398. if ($this->inCondition and!$this->conditionIsTrue)
  1399. return $this;
  1400. $this->sql .= " < " . $this->quote($value);
  1401. return $this;
  1402. }
  1403. /**
  1404. * Create '<='.
  1405. *
  1406. * @param mixed $value
  1407. * @access public
  1408. * @return object the sql object.
  1409. */
  1410. public function le($value) {
  1411. if ($this->inCondition && !$this->conditionIsTrue) {
  1412. return $this;
  1413. }
  1414. $this->sql .= " <= " . $this->quote($value);
  1415. return $this;
  1416. }
  1417. /**
  1418. * Create "between and"
  1419. *
  1420. * @param string $min
  1421. * @param string $max
  1422. * @access public
  1423. * @return object the sql object.
  1424. */
  1425. public function between($min, $max) {
  1426. if ($this->inCondition and!$this->conditionIsTrue)
  1427. return $this;
  1428. $min = $this->quote($min);
  1429. $max = $this->quote($max);
  1430. $this->sql .= " BETWEEN $min AND $max ";
  1431. return $this;
  1432. }
  1433. /**
  1434. * Create in part.
  1435. *
  1436. * @param string|array $ids list string by ',' or an array
  1437. * @access public
  1438. * @return object the sql object.
  1439. */
  1440. public function in($ids) {
  1441. // var_dump($ids);
  1442. if ($this->inCondition and!$this->conditionIsTrue)
  1443. return $this;
  1444. $this->sql .= self::dbIN($ids);
  1445. return $this;
  1446. }
  1447. /**
  1448. * Create the in('a', 'b') string.
  1449. *
  1450. * @param string|array $ids the id lists, can be a array or a string with ids joined with comma.
  1451. * @static
  1452. * @access public
  1453. * @return string the string like IN('a', 'b').
  1454. */
  1455. private static function dbIN($ids) {
  1456. if (is_array($ids))
  1457. return "IN ('" . join("','", $ids) . "')";
  1458. return "IN ('" . str_replace(',', "','", str_replace(' ', '', $ids)) . "')";
  1459. }
  1460. /**
  1461. * Create not in part.
  1462. *
  1463. * @param string|array $ids list string by ',' or an array
  1464. * @access public
  1465. * @return object the sql object.
  1466. */
  1467. public function notin($ids) {
  1468. if ($this->inCondition and!$this->conditionIsTrue)
  1469. return $this;
  1470. $this->sql .= ' NOT ' . self::dbIN($ids);
  1471. return $this;
  1472. }
  1473. /**
  1474. * Create the like by part.
  1475. *
  1476. * @param string $string
  1477. * @access public
  1478. * @return object the sql object.
  1479. */
  1480. public function like($string) {
  1481. if ($this->inCondition and!$this->conditionIsTrue)
  1482. return $this;
  1483. $this->sql .= " LIKE " . $this->quote($string);
  1484. return $this;
  1485. }
  1486. /**
  1487. * Create the not like by part.
  1488. *
  1489. * @param string $string
  1490. * @access public
  1491. * @return object the sql object.
  1492. */
  1493. public function notLike($string) {
  1494. if ($this->inCondition and!$this->conditionIsTrue)
  1495. return $this;
  1496. $this->sql .= "NOT LIKE " . $this->quote($string);
  1497. return $this;
  1498. }
  1499. /**
  1500. * Create the find_in_set by part.
  1501. *
  1502. * @param int $str
  1503. * @param int $strList
  1504. * @access public
  1505. * @return object the sql object.
  1506. */
  1507. public function findInSet($str, $strList) {
  1508. if ($this->inCondition and!$this->conditionIsTrue)
  1509. return $this;
  1510. $this->sql .= "FIND_IN_SET(" . $str . "," . $strList . ")";
  1511. }
  1512. /**
  1513. * Create the order by part.
  1514. *
  1515. * @param string $order
  1516. * @access public
  1517. * @return object the sql object.
  1518. */
  1519. public function orderBy($order) {
  1520. if ($this->inCondition and!$this->conditionIsTrue)
  1521. return $this;
  1522. $order = str_replace(array('|', '', '_'), ' ', $order);
  1523. /* Add "`" in order string. */
  1524. /* When order has limit string. */
  1525. $pos = stripos($order, 'limit');
  1526. $orders = $pos ? substr($order, 0, $pos) : $order;
  1527. $limit = $pos ? substr($order, $pos) : '';
  1528. $orders = explode(',', $orders);
  1529. foreach ($orders as $i => $order) {
  1530. $orderParse = explode(' ', trim($order));
  1531. foreach ($orderParse as $key => $value) {
  1532. $value = trim($value);
  1533. if (empty($value) or strtolower($value) == 'desc' or strtolower($value) == 'asc')
  1534. continue;
  1535. $field = trim($value, '`');
  1536. /* such as t1.id field. */
  1537. if (strpos($value, '.') !== false)
  1538. list($table, $field) = explode('.', $field);
  1539. $field = "`$field`";
  1540. $orderParse[$key] = isset($table) ? $table . '.' . $field : $field;
  1541. unset($table);
  1542. }
  1543. $orders[$i] = join(' ', $orderParse);
  1544. }
  1545. $order = join(',', $orders) . ' ' . $limit;
  1546. $this->sql .= ' ' . DAO::ORDERBY . " $order";
  1547. return $this;
  1548. }
  1549. /**
  1550. * Create the limit part.
  1551. *
  1552. * @param string $limit
  1553. * @access public
  1554. * @return object the sql object.
  1555. */
  1556. public function limit($limit) {
  1557. if (empty($limit))
  1558. return $this;
  1559. stripos($limit, 'limit') !== false ? $this->sql .= " $limit " : $this->sql .= ' ' . DAO::LIMIT . " $limit ";
  1560. return $this;
  1561. }
  1562. /**
  1563. * Create the groupby part.
  1564. *
  1565. * @param string $groupBy
  1566. * @access public
  1567. * @return object the sql object.
  1568. */
  1569. public function groupBy($groupBy) {
  1570. $this->sql .= ' ' . DAO::GROUPBY . " $groupBy";
  1571. return $this;
  1572. }
  1573. /**
  1574. * Create the having part.
  1575. *
  1576. * @param string $having
  1577. * @access public
  1578. * @return object the sql object.
  1579. */
  1580. public function having($having) {
  1581. $this->sql .= ' ' . DAO::HAVING . " $having";
  1582. return $this;
  1583. }
  1584. /**
  1585. * Get the sql string.
  1586. *
  1587. * @access public
  1588. * @return string
  1589. */
  1590. public function get() {
  1591. return $this->sql;
  1592. }
  1593. /**
  1594. * Uuote a var.
  1595. *
  1596. * @param mixed $value
  1597. * @access public
  1598. * @return mixed
  1599. */
  1600. public function quote($value) {
  1601. // var_dump($value);
  1602. if ($this->magicQuote) {
  1603. $value = stripslashes($value);
  1604. }
  1605. return $this->dbh->quote($value);
  1606. }
  1607. }