dao.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  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. /**
  901. * Log the error.
  902. *
  903. * For the error notice, see module/common/lang.
  904. *
  905. * @param string $checkType the check rule
  906. * @param string $fieldName the field name
  907. * @param string $fieldLabel the field label
  908. * @param array $funcArgs the args
  909. * @access public
  910. * @return void
  911. */
  912. public function logError($checkType, $fieldName, $fieldLabel, $funcArgs = array()) {
  913. global $lang;
  914. $error = $lang->error->$checkType;
  915. $replaces = array_merge(array($fieldLabel), $funcArgs); // the replace values.
  916. /* Just a string, cycle the $replaces. */
  917. if (!is_array($error)) {
  918. foreach ($replaces as $replace) {
  919. $pos = strpos($error, '%s');
  920. if ($pos === false)
  921. break;
  922. $error = substr($error, 0, $pos) . $replace . substr($error, $pos + 2);
  923. }
  924. }
  925. /* If the error define is an array, select the one which %s counts match the $replaces. */ else {
  926. /* Remove the empty items. */
  927. foreach ($replaces as $key => $value)
  928. if (is_null($value))
  929. unset($replaces[$key]);
  930. $replacesCount = count($replaces);
  931. foreach ($error as $errorString) {
  932. if (substr_count($errorString, '%s') == $replacesCount) {
  933. $error = vsprintf($errorString, $replaces);
  934. }
  935. }
  936. }
  937. dao::$errors[$fieldName][] = $error;
  938. }
  939. /**
  940. * Judge any error or not.
  941. *
  942. * @access public
  943. * @return bool
  944. */
  945. public static function isError() {
  946. return !empty(dao::$errors);
  947. }
  948. /**
  949. * Get the errors.
  950. *
  951. * @param boolean $join
  952. * @access public
  953. * @return array
  954. */
  955. public static function getError($join = false) {
  956. $errors = dao::$errors;
  957. dao::$errors = array(); // Must clear it.
  958. if (!$join)
  959. return $errors;
  960. if (is_array($errors)) {
  961. $message = '';
  962. foreach ($errors as $item) {
  963. is_array($item) ? $message .= join('\n', $item) . '\n' : $message .= $item . '\n';
  964. }
  965. return $message;
  966. }
  967. }
  968. /**
  969. * Get the defination of fields of the table.
  970. *
  971. * @access private
  972. * @return array
  973. */
  974. private function getFieldsType() {
  975. try {
  976. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
  977. $sql = "DESC $this->table";
  978. $rawFields = $this->dbh->query($sql)->fetchAll();
  979. $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  980. } catch (PDOException $e) {
  981. $this->sqlError($e);
  982. }
  983. foreach ($rawFields as $rawField) {
  984. $firstPOS = strpos($rawField->type, '(');
  985. $type = substr($rawField->type, 0, $firstPOS > 0 ? $firstPOS : strlen($rawField->type));
  986. $type = str_replace(array('big', 'small', 'medium', 'tiny', 'var'), '', $type);
  987. $field = array();
  988. if ($type == 'enum' or $type == 'set') {
  989. $rangeBegin = $firstPOS + 2; // Remove the first quote.
  990. $rangeEnd = strrpos($rawField->type, ')') - 1; // Remove the last quote.
  991. $range = substr($rawField->type, $rangeBegin, $rangeEnd - $rangeBegin);
  992. $field['rule'] = 'reg';
  993. $field['options']['reg'] = '/' . str_replace("','", '|', $range) . '/';
  994. } elseif ($type == 'char') {
  995. $begin = $firstPOS + 1;
  996. $end = strpos($rawField->type, ')', $begin);
  997. $length = substr($rawField->type, $begin, $end - $begin);
  998. $field['rule'] = 'length';
  999. $field['options']['max'] = $length;
  1000. $field['options']['min'] = 0;
  1001. } elseif ($type == 'int') {
  1002. $field['rule'] = 'int';
  1003. } elseif ($type == 'float' or $type == 'double') {
  1004. $field['rule'] = 'float';
  1005. } elseif ($type == 'date') {
  1006. $field['rule'] = 'date';
  1007. } else {
  1008. $field['rule'] = 'skip';
  1009. }
  1010. $fields[$rawField->field] = $field;
  1011. }
  1012. return $fields;
  1013. }
  1014. /**
  1015. * Process SQL error by code.
  1016. *
  1017. * @param object $exception
  1018. * @access public
  1019. * @return void
  1020. */
  1021. public function sqlError($exception) {
  1022. $errorInfo = $exception->errorInfo;
  1023. $errorCode = $errorInfo[1];
  1024. $errorMsg = $errorInfo[2];
  1025. $message = $exception->getMessage();
  1026. if (strpos($this->repairCode, "|$errorCode|") !== false #
  1027. or ( $errorCode == '1016' and strpos($errorMsg, 'errno: 145') !== false)) {
  1028. $message .= ' repairTable';
  1029. }
  1030. $sql = $this->sqlobj->get();
  1031. $this->triggerError($message . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
  1032. }
  1033. }
  1034. /**
  1035. * The SQL class.
  1036. *
  1037. * @package framework
  1038. */
  1039. class sql {
  1040. /**
  1041. * The max count of params of all methods.
  1042. *
  1043. */
  1044. const MAX_ARGS = 3;
  1045. /**
  1046. * The sql string.
  1047. *
  1048. * @var string
  1049. * @access public
  1050. */
  1051. public $sql = '';
  1052. /**
  1053. * The global $dbh.
  1054. *
  1055. *
  1056. * @access protected
  1057. */
  1058. protected $dbh;
  1059. /**
  1060. * The data to update or insert.
  1061. *
  1062. * @var mix
  1063. * @access protected
  1064. */
  1065. public $data;
  1066. /**
  1067. * Is the first time to call set.
  1068. *
  1069. * @var bool
  1070. * @access private;
  1071. */
  1072. private $isFirstSet = true;
  1073. /**
  1074. * If in the logic of judge condition or not.
  1075. *
  1076. * @var bool
  1077. * @access private;
  1078. */
  1079. private $inCondition = false;
  1080. /**
  1081. * The condition is true or not.
  1082. *
  1083. * @var bool
  1084. * @access private;
  1085. */
  1086. private $conditionIsTrue = false;
  1087. /**
  1088. * Magic quote or not.
  1089. *
  1090. * @var bool
  1091. * @access public
  1092. */
  1093. public $magicQuote;
  1094. /**
  1095. * The construct function. user factory() to instance it.
  1096. *
  1097. * @param string $table
  1098. * @access private
  1099. * @return void
  1100. */
  1101. private function __construct($table = '') {
  1102. global $dbh;
  1103. $this->dbh = $dbh;
  1104. $this->magicQuote = get_magic_quotes_gpc();
  1105. }
  1106. /**
  1107. * The factory method.
  1108. *
  1109. * @param string $table
  1110. * @access public
  1111. * @return object the sql object.
  1112. */
  1113. public static function factory($table = '') {
  1114. return new sql($table);
  1115. }
  1116. /**
  1117. * The sql is select.
  1118. *
  1119. * @param string $field
  1120. * @access public
  1121. * @return object the sql object.
  1122. */
  1123. public static function select($field = '*') {
  1124. $sqlobj = self::factory();
  1125. $sqlobj->sql = "SELECT $field ";
  1126. return $sqlobj;
  1127. }
  1128. /**
  1129. * The sql is update.
  1130. *
  1131. * @param string $table
  1132. * @access public
  1133. * @return object the sql object.
  1134. */
  1135. public static function update($table) {
  1136. $sqlobj = self::factory();
  1137. $sqlobj->sql = "UPDATE $table SET ";
  1138. return $sqlobj;
  1139. }
  1140. /**
  1141. * The sql is insert.
  1142. *
  1143. * @param string $table
  1144. * @access public
  1145. * @return object the sql object.
  1146. */
  1147. public static function insert($table) {
  1148. $sqlobj = self::factory();
  1149. $sqlobj->sql = "INSERT INTO $table SET ";
  1150. return $sqlobj;
  1151. }
  1152. /**
  1153. * The sql is replace.
  1154. *
  1155. * @param string $table
  1156. * @access public
  1157. * @return object the sql object.
  1158. */
  1159. public static function replace($table) {
  1160. $sqlobj = self::factory();
  1161. $sqlobj->sql = "REPLACE $table SET ";
  1162. return $sqlobj;
  1163. }
  1164. /**
  1165. * The sql is delete.
  1166. *
  1167. * @access public
  1168. * @return object the sql object.
  1169. */
  1170. public static function delete() {
  1171. $sqlobj = self::factory();
  1172. $sqlobj->sql = "DELETE ";
  1173. return $sqlobj;
  1174. }
  1175. /**
  1176. * Join the data items by key = value.
  1177. *
  1178. * @param object $data
  1179. * @access public
  1180. * @return object the sql object.
  1181. */
  1182. public function data($data) {
  1183. $data = (object) $data;
  1184. foreach ($data as $field => $value) {
  1185. if (!preg_match('|^\w+$|', $field)) {
  1186. unset($data->$field);
  1187. continue;
  1188. }
  1189. $this->sql .= "`$field` = " . $this->quote($value) . ',';
  1190. }
  1191. $this->data = $data;
  1192. $this->sql = rtrim($this->sql, ','); // Remove the last ','.
  1193. return $this;
  1194. }
  1195. /**
  1196. * Aadd an '(' at left.
  1197. *
  1198. * @param int $count
  1199. * @access public
  1200. * @return ojbect the sql object.
  1201. */
  1202. public function markLeft($count = 1) {
  1203. $this->sql .= str_repeat('(', $count);
  1204. return $this;
  1205. }
  1206. /**
  1207. * Add an ')' ad right.
  1208. *
  1209. * @param int $count
  1210. * @access public
  1211. * @return object the sql object.
  1212. */
  1213. public function markRight($count = 1) {
  1214. $this->sql .= str_repeat(')', $count);
  1215. return $this;
  1216. }
  1217. /**
  1218. * The set part.
  1219. *
  1220. * @param string $set
  1221. * @access public
  1222. * @return object the sql object.
  1223. */
  1224. public function set($set) {
  1225. if ($this->isFirstSet) {
  1226. $this->sql .= " $set ";
  1227. $this->isFirstSet = false;
  1228. } else {
  1229. $this->sql .= ", $set";
  1230. }
  1231. return $this;
  1232. }
  1233. /**
  1234. * Create the from part.
  1235. *
  1236. * @param string $table
  1237. * @access public
  1238. * @return object the sql object.
  1239. */
  1240. public function from($table) {
  1241. $this->sql .= "FROM $table";
  1242. return $this;
  1243. }
  1244. /**
  1245. * Create the Alias part.
  1246. *
  1247. * @param string $alias
  1248. * @access public
  1249. * @return object the sql object.
  1250. */
  1251. public function alias($alias) {
  1252. $this->sql .= " AS $alias ";
  1253. return $this;
  1254. }
  1255. /**
  1256. * Create the left join part.
  1257. *
  1258. * @param string $table
  1259. * @access public
  1260. * @return object the sql object.
  1261. */
  1262. public function leftJoin($table) {
  1263. $this->sql .= " LEFT JOIN $table";
  1264. return $this;
  1265. }
  1266. /**
  1267. * Create the on part.
  1268. *
  1269. * @param string $condition
  1270. * @access public
  1271. * @return object the sql object.
  1272. */
  1273. public function on($condition) {
  1274. $this->sql .= " ON $condition ";
  1275. return $this;
  1276. }
  1277. /**
  1278. * Begin condition judge.
  1279. *
  1280. * @param bool $condition
  1281. * @access public
  1282. * @return object the sql object.
  1283. */
  1284. public function beginIF($condition) {
  1285. $this->inCondition = true;
  1286. $this->conditionIsTrue = $condition;
  1287. return $this;
  1288. }
  1289. /**
  1290. * End the condition judge.
  1291. *
  1292. * @access public
  1293. * @return object the sql object.
  1294. */
  1295. public function fi() {
  1296. $this->inCondition = false;
  1297. $this->conditionIsTrue = false;
  1298. return $this;
  1299. }
  1300. /**
  1301. * Create the where part.
  1302. *
  1303. * @param string $arg1 the field name
  1304. * @param string $arg2 the operator
  1305. * @param string $arg3 the value
  1306. * @access public
  1307. * @return object the sql object.
  1308. */
  1309. public function where($arg1, $arg2 = null, $arg3 = null) {
  1310. if ($this->inCondition and!$this->conditionIsTrue)
  1311. return $this;
  1312. if ($arg3 !== null) {
  1313. $value = $this->quote($arg3);
  1314. $condition = "`$arg1` $arg2 " . $this->quote($arg3);
  1315. } else {
  1316. $condition = $arg1;
  1317. }
  1318. $this->sql .= ' ' . DAO::WHERE . " $condition ";
  1319. return $this;
  1320. }
  1321. /**
  1322. * Create the AND part.
  1323. *
  1324. * @param string $condition
  1325. * @access public
  1326. * @return object the sql object.
  1327. */
  1328. public function andWhere($condition) {
  1329. if ($this->inCondition and!$this->conditionIsTrue)
  1330. return $this;
  1331. $this->sql .= " AND $condition ";
  1332. return $this;
  1333. }
  1334. /**
  1335. * Create the OR part.
  1336. *
  1337. * @param bool $condition
  1338. * @access public
  1339. * @return object the sql object.
  1340. */
  1341. public function orWhere($condition) {
  1342. if ($this->inCondition and!$this->conditionIsTrue)
  1343. return $this;
  1344. $this->sql .= " OR $condition ";
  1345. return $this;
  1346. }
  1347. /**
  1348. * Create the '='.
  1349. *
  1350. * @param string $value
  1351. * @access public
  1352. * @return object the sql object.
  1353. */
  1354. public function eq($value) {
  1355. if ($this->inCondition and!$this->conditionIsTrue)
  1356. return $this;
  1357. $this->sql .= " = " . $this->quote($value);
  1358. return $this;
  1359. }
  1360. /**
  1361. * Create '!='.
  1362. *
  1363. * @param string $value
  1364. * @access public
  1365. * @return void the sql object.
  1366. */
  1367. public function ne($value) {
  1368. if ($this->inCondition and!$this->conditionIsTrue)
  1369. return $this;
  1370. $this->sql .= " != " . $this->quote($value);
  1371. return $this;
  1372. }
  1373. /**
  1374. * Create '>'.
  1375. *
  1376. * @param string $value
  1377. * @access public
  1378. * @return object the sql object.
  1379. */
  1380. public function gt($value) {
  1381. if ($this->inCondition and!$this->conditionIsTrue)
  1382. return $this;
  1383. $this->sql .= " > " . $this->quote($value);
  1384. return $this;
  1385. }
  1386. /**
  1387. * Create '>='.
  1388. *
  1389. * @param string $value
  1390. * @access public
  1391. * @return object the sql object.
  1392. */
  1393. public function ge($value) {
  1394. if ($this->inCondition and!$this->conditionIsTrue)
  1395. return $this;
  1396. $this->sql .= " >= " . $this->quote($value);
  1397. return $this;
  1398. }
  1399. /**
  1400. * Create '<'.
  1401. *
  1402. * @param mixed $value
  1403. * @access public
  1404. * @return object the sql object.
  1405. */
  1406. public function lt($value) {
  1407. if ($this->inCondition and!$this->conditionIsTrue)
  1408. return $this;
  1409. $this->sql .= " < " . $this->quote($value);
  1410. return $this;
  1411. }
  1412. /**
  1413. * Create '<='.
  1414. *
  1415. * @param mixed $value
  1416. * @access public
  1417. * @return object the sql object.
  1418. */
  1419. public function le($value) {
  1420. if ($this->inCondition && !$this->conditionIsTrue) {
  1421. return $this;
  1422. }
  1423. $this->sql .= " <= " . $this->quote($value);
  1424. return $this;
  1425. }
  1426. /**
  1427. * Create "between and"
  1428. *
  1429. * @param string $min
  1430. * @param string $max
  1431. * @access public
  1432. * @return object the sql object.
  1433. */
  1434. public function between($min, $max) {
  1435. if ($this->inCondition and!$this->conditionIsTrue)
  1436. return $this;
  1437. $min = $this->quote($min);
  1438. $max = $this->quote($max);
  1439. $this->sql .= " BETWEEN $min AND $max ";
  1440. return $this;
  1441. }
  1442. /**
  1443. * Create in part.
  1444. *
  1445. * @param string|array $ids list string by ',' or an array
  1446. * @access public
  1447. * @return object the sql object.
  1448. */
  1449. public function in($ids) {
  1450. // var_dump($ids);
  1451. if ($this->inCondition and!$this->conditionIsTrue)
  1452. return $this;
  1453. $this->sql .= self::dbIN($ids);
  1454. return $this;
  1455. }
  1456. /**
  1457. * Create the in('a', 'b') string.
  1458. *
  1459. * @param string|array $ids the id lists, can be a array or a string with ids joined with comma.
  1460. * @static
  1461. * @access public
  1462. * @return string the string like IN('a', 'b').
  1463. */
  1464. private static function dbIN($ids) {
  1465. if (is_array($ids))
  1466. return "IN ('" . join("','", $ids) . "')";
  1467. return "IN ('" . str_replace(',', "','", str_replace(' ', '', $ids)) . "')";
  1468. }
  1469. /**
  1470. * Create not in part.
  1471. *
  1472. * @param string|array $ids list string by ',' or an array
  1473. * @access public
  1474. * @return object the sql object.
  1475. */
  1476. public function notin($ids) {
  1477. if ($this->inCondition and!$this->conditionIsTrue)
  1478. return $this;
  1479. $this->sql .= ' NOT ' . self::dbIN($ids);
  1480. return $this;
  1481. }
  1482. /**
  1483. * Create the like by part.
  1484. *
  1485. * @param string $string
  1486. * @access public
  1487. * @return object the sql object.
  1488. */
  1489. public function like($string) {
  1490. if ($this->inCondition and!$this->conditionIsTrue)
  1491. return $this;
  1492. $this->sql .= " LIKE " . $this->quote($string);
  1493. return $this;
  1494. }
  1495. /**
  1496. * Create the not like by part.
  1497. *
  1498. * @param string $string
  1499. * @access public
  1500. * @return object the sql object.
  1501. */
  1502. public function notLike($string) {
  1503. if ($this->inCondition and!$this->conditionIsTrue)
  1504. return $this;
  1505. $this->sql .= "NOT LIKE " . $this->quote($string);
  1506. return $this;
  1507. }
  1508. /**
  1509. * Create the find_in_set by part.
  1510. *
  1511. * @param int $str
  1512. * @param int $strList
  1513. * @access public
  1514. * @return object the sql object.
  1515. */
  1516. public function findInSet($str, $strList) {
  1517. if ($this->inCondition and!$this->conditionIsTrue)
  1518. return $this;
  1519. $this->sql .= "FIND_IN_SET(" . $str . "," . $strList . ")";
  1520. }
  1521. /**
  1522. * Create the order by part.
  1523. *
  1524. * @param string $order
  1525. * @access public
  1526. * @return object the sql object.
  1527. */
  1528. public function orderBy($order) {
  1529. if ($this->inCondition and!$this->conditionIsTrue)
  1530. return $this;
  1531. $order = str_replace(array('|', '', '_'), ' ', $order);
  1532. /* Add "`" in order string. */
  1533. /* When order has limit string. */
  1534. $pos = stripos($order, 'limit');
  1535. $orders = $pos ? substr($order, 0, $pos) : $order;
  1536. $limit = $pos ? substr($order, $pos) : '';
  1537. $orders = explode(',', $orders);
  1538. foreach ($orders as $i => $order) {
  1539. $orderParse = explode(' ', trim($order));
  1540. foreach ($orderParse as $key => $value) {
  1541. $value = trim($value);
  1542. if (empty($value) or strtolower($value) == 'desc' or strtolower($value) == 'asc')
  1543. continue;
  1544. $field = trim($value, '`');
  1545. /* such as t1.id field. */
  1546. if (strpos($value, '.') !== false)
  1547. list($table, $field) = explode('.', $field);
  1548. $field = "`$field`";
  1549. $orderParse[$key] = isset($table) ? $table . '.' . $field : $field;
  1550. unset($table);
  1551. }
  1552. $orders[$i] = join(' ', $orderParse);
  1553. }
  1554. $order = join(',', $orders) . ' ' . $limit;
  1555. $this->sql .= ' ' . DAO::ORDERBY . " $order";
  1556. return $this;
  1557. }
  1558. /**
  1559. * Create the limit part.
  1560. *
  1561. * @param string $limit
  1562. * @access public
  1563. * @return object the sql object.
  1564. */
  1565. public function limit($limit) {
  1566. if (empty($limit))
  1567. return $this;
  1568. stripos($limit, 'limit') !== false ? $this->sql .= " $limit " : $this->sql .= ' ' . DAO::LIMIT . " $limit ";
  1569. return $this;
  1570. }
  1571. /**
  1572. * Create the groupby part.
  1573. *
  1574. * @param string $groupBy
  1575. * @access public
  1576. * @return object the sql object.
  1577. */
  1578. public function groupBy($groupBy) {
  1579. $this->sql .= ' ' . DAO::GROUPBY . " $groupBy";
  1580. return $this;
  1581. }
  1582. /**
  1583. * Create the having part.
  1584. *
  1585. * @param string $having
  1586. * @access public
  1587. * @return object the sql object.
  1588. */
  1589. public function having($having) {
  1590. $this->sql .= ' ' . DAO::HAVING . " $having";
  1591. return $this;
  1592. }
  1593. /**
  1594. * Get the sql string.
  1595. *
  1596. * @access public
  1597. * @return string
  1598. */
  1599. public function get() {
  1600. return $this->sql;
  1601. }
  1602. /**
  1603. * Uuote a var.
  1604. *
  1605. * @param mixed $value
  1606. * @access public
  1607. * @return mixed
  1608. */
  1609. public function quote($value) {
  1610. if ($this->magicQuote)
  1611. $value = stripslashes($value);
  1612. return $this->dbh->quote($value);
  1613. }
  1614. }