dao.php 49 KB

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