dao.php 50 KB

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