dao.php 49 KB

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