dao.php 49 KB

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