dao.php 49 KB

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