dao.php 48 KB

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