Advertisement
d4nt1

pdo

Feb 14th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.18 KB | None | 0 0
  1. <?php
  2. if ( ! defined('ABS_PATH')) exit('ABS_PATH is not loaded. Direct access is not allowed.');
  3.  
  4. class db extends PDO {
  5. private $error;
  6. private $sql;
  7. private $bind = array();
  8. private $type;
  9. private $table;
  10. private $alias;
  11. private $jointables;
  12. private $fields = array();
  13. private $where = "";
  14. private $between = "";
  15. private $like = "";
  16. private $groupby;
  17. private $having = "";
  18. private $orderby;
  19. private $limit;
  20. private $on_duplicate;
  21. private $stmt;
  22. private $errorCallbackFunction;
  23. private $errorMsgFormat;
  24.  
  25. /**
  26. * Create a new db object.
  27. * @param string $dsn The dsn string.
  28. * @param string $user [optional] <p>The database user name.</p>
  29. * @param string $passwd [optional] <p>The database password.</p>
  30. * @param array $options [optional] <p>A key=>value array of driver-specific connection options.<p>
  31. * @param string $errorCallbackFunction [optional] <p>The callback function to show errors (e.g. "print", "echo", ...).</p>
  32. * @param string $errorFormat [optional] <p>The format to display errors ("html" or "text").</p>
  33. */
  34. public function __construct($dsn=NULL, $user=NULL, $passwd=NULL, $errorCallbackFunction = NULL, $errorFormat = NULL) {
  35. $options = array(
  36. PDO::ATTR_PERSISTENT => true,
  37. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  38. );
  39. if(empty($dsn)){
  40. $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ';charset=' . DB_ENCODING;
  41. //$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
  42. }
  43.  
  44. if(empty($user)){
  45. $user = DB_USER;
  46. }
  47.  
  48. if(empty($passwd)){
  49. $passwd = DB_PASSWORD;
  50. }
  51.  
  52. if(empty ($errorCallbackFunction)){
  53. $errorCallbackFunction = "print_r";
  54. }
  55.  
  56. if(empty ($errorFormat)){
  57. $errorFormat = "html";
  58. }
  59.  
  60. if (strtolower($errorFormat) !== "html"){
  61. $errorFormat == "text";
  62. }
  63.  
  64. $this->errorMsgFormat == strtolower($errorFormat);
  65. $this->errorCallbackFunction = $errorCallbackFunction;
  66.  
  67. try {
  68. parent::__construct($dsn, $user, $passwd, $options);
  69. $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('dbStatement'));
  70. } catch (PDOException $e) {
  71. $this->error = $e->getMessage();
  72. }
  73. }
  74.  
  75. /**
  76. * Prepares a statement for execution and returns a statement object
  77. * @param string $statement <p>
  78. * This must be a valid SQL statement for the target database server.
  79. * </p>
  80. * @param array $driver_options [optional] <p>
  81. * This array holds one or more key=&gt;value pairs to set
  82. * attribute values for the PDOStatement object that this method
  83. * returns. You would most commonly use this to set the
  84. * PDO::ATTR_CURSOR value to
  85. * PDO::CURSOR_SCROLL to request a scrollable cursor.
  86. * Some drivers have driver specific options that may be set at
  87. * prepare-time.
  88. * </p>
  89. * @return dbStatement If the database server successfully prepares the statement unless otherwise specified in the $driver_options argument,
  90. * db::prepare returns a
  91. * dbStatement object.
  92. * If the database server cannot successfully prepare the statement,
  93. * db::prepare returns false or emits
  94. * PDOException (depending on error handling).
  95. * </p>
  96. * <p>
  97. * Emulated prepared statements does not communicate with the database server
  98. * so db::prepare does not check the statement.
  99. */
  100. public function prepare($sql, $driver_options = array()) {
  101. if(!isset($driver_options[PDO::ATTR_STATEMENT_CLASS])){
  102. $driver_options[PDO::ATTR_STATEMENT_CLASS] = array('dbStatement');
  103. }
  104. return parent::prepare($sql, $driver_options);
  105. }
  106.  
  107. /**
  108. * Build a select query.
  109. * @param string $table The table name.
  110. * @param array $fields [optional] <p>An array with the column names you want to select as values.</p>
  111. * @return db
  112. */
  113. public function select($table, array $fields = NULL) {
  114. $this->reset();
  115. $this->type = 'select';
  116. $table = trim($table);
  117. if(strpos($table, " ")){
  118. $this->table = trim(substr($table, 0, strpos($table, " ")));
  119. $this->alias = trim(substr($table, strpos($table, " ")));
  120. }
  121. else{
  122. $this->table = $table;
  123. }
  124. if (!empty($fields)){
  125. $this->fields($fields);
  126. }
  127. return $this;
  128. }
  129.  
  130. /**
  131. * Build an insert query.
  132. * @param string $table The table to insert the data into.
  133. * @param array $fields [optional] <p>An array with the column names as keys and the values you want to insert as values.</p>
  134. * @return db
  135. */
  136. public function insert($table, array $fields = NULL) {
  137. $this->reset();
  138. $this->type = 'insert';
  139. $this->table = $table;
  140. if(!empty($fields)){
  141. $this->fields($fields);
  142. }
  143. return $this;
  144. }
  145.  
  146. /**
  147. * Build an update query.
  148. * @param string $table The table you want to update.
  149. * @param array $fields [optional] <p>An array with the column names as keys and the values you want to insert as values.</p>
  150. * @return db
  151. */
  152. public function update($table, array $fields = NULL) {
  153. $this->reset();
  154. $this->type = 'update';
  155. $this->table = $table;
  156. if(!empty($fields)){
  157. $this->fields($fields);
  158. }
  159. return $this;
  160. }
  161.  
  162. /**
  163. * Build a delete query.
  164. * @param string $table The table you want to delete data from.
  165. * @return db
  166. */
  167. public function delete($table) {
  168. $this->reset();
  169. $this->type = 'delete';
  170. $this->table = $table;
  171. return $this;
  172. }
  173.  
  174. /**
  175. * Add fields to the query
  176. * @param array $fields <p>An array with the column names as keys and the values you want to insert as values for update and insert statements.</p><p>An array with the column names you want to select as values for select statements.</p>
  177. * @return db
  178. */
  179. public function fields(array $fields){
  180. switch ($this->type) {
  181. case 'insert':
  182. case 'update':
  183. if(!empty($fields)){
  184. $this->fields += array_keys($fields);
  185. //$this->sql .= " (" . implode($fields, ", ") . ") VALUES (:" . implode($fields, ", :") . ")";
  186. $bind = array();
  187. foreach($this->fields as $field) {
  188. $key = str_replace('.', '', $field);
  189. $i = 0;
  190. while(isset($this->bind[":$key"]) || isset($bind[":$key"])){
  191. $key = str_replace('.', '', $field) . $i;
  192. }
  193. $bind[":$key"] = $fields[$field];
  194. }
  195. $this->bind += $this->cleanup($bind);
  196. }
  197. break;
  198.  
  199. case 'select':
  200. if(!empty($fields)){
  201. $this->fields += $fields;
  202. }
  203. break;
  204.  
  205. default:
  206. break;
  207. }
  208. return $this;
  209. }
  210.  
  211. /**
  212. * Add a join part to the query.
  213. * @param string $table The table to join with.
  214. * @param string $condition [optional] <p>The join condition.</p>
  215. * @return db
  216. */
  217. public function join($table, $condition = NULL) {
  218. return $this->addJoin('INNER', $table, $condition);
  219. }
  220.  
  221. /**
  222. * Add an inner join part to the query.
  223. * @param string $table The table to join with.
  224. * @param string $condition [optional] <p>The join condition.</p>
  225. * @return db
  226. */
  227. public function innerJoin($table, $condition = NULL) {
  228. return $this->addJoin('INNER', $table, $condition);
  229. }
  230.  
  231. /**
  232. * Add a left join part to the query.
  233. * @param string $table The table to join with.
  234. * @param string $condition [optional] <p>The join condition.</p>
  235. * @return db
  236. */
  237. public function leftJoin($table, $condition = NULL) {
  238. return $this->addJoin('LEFT OUTER', $table, $condition);
  239. }
  240.  
  241. /**
  242. * Add a right join part to the query.
  243. * @param string $table The table to join with.
  244. * @param string $condition [optional] <p>The join condition.</p>
  245. * @return db
  246. */
  247. public function rightJoin($table, $condition = NULL) {
  248. return $this->addJoin('RIGHT OUTER', $table, $condition);
  249. }
  250.  
  251. /**
  252. * Add a join part to the query.
  253. * @param string $table The table to join with.
  254. * @param string $type The join type ("INNER", "LEFT OUTER", "RIGHT OUTER").
  255. * @param string $condition [optional] <p>The join condition.</p>
  256. * @return db
  257. */
  258. public function addJoin($type, $table, $condition = NULL) {
  259. $orig_alias = trim(substr($table, strpos($table, " ")));
  260. $alias = $orig_alias;
  261. $alias_candidate = $alias;
  262. $count = 2;
  263. while (!empty($this->jointables[$alias_candidate])) {
  264. $alias_candidate = $alias . '_' . $count++;
  265. }
  266.  
  267. $alias = $alias_candidate;
  268. $condition = str_replace($orig_alias, $alias, $condition);
  269.  
  270. $this->jointables[$alias] = array(
  271. 'join type' => $type,
  272. 'table' => trim(substr($table, 0, strpos($table, " "))),
  273. 'alias' => $alias,
  274. 'condition' => $condition,
  275. );
  276.  
  277. return $this;
  278. }
  279. /**
  280. * Add a where clause to the query.
  281. * @param string $field The column to wich this clause applies.
  282. * @param mixed $value [optional]
  283. * <p>The value to compare the column with.</p>
  284. * <p>Leave this parameter and the operator parameter blank (NULL) to have the "IS NULL" operator (WHERE column IS NULL).</p>
  285. * <p>If this parameter is an array and no operator is given the "IN" operator will be used (WHERE column IN (value1, value2).</p>
  286. * <p>If this parameter is an array you can also specify the "NOT IN" operator as the next parameter (WHERE column NOT IN (value1, value2).</p>
  287. * <p>If this parameter is a string and no operator is given the "=" operator will be used (WHERE column = value).</p>
  288. * @param string $operator [optional] <p>The operator that will be used (e.g. "IS NULL", "IN", "NOT IN", "=", "<>", ...).</p>
  289. * @param string $concatenator [optional] <p>Leave empty if this is the first where clause of the query.</p>
  290. * <p>Possible values "AND" and "OR". You can also use the andwhere and orwhere functions of this class.</p>
  291. * @return db
  292. */
  293. public function like($field){
  294. if(is_array($field))
  295. {
  296. $this->like .= $field[0] . ' LIKE ? ';
  297. for($i=1;$i<count($field);$i++)
  298. {
  299. $this->like .= 'OR ' . $field[$i] . ' LIKE ? ';
  300. }
  301. return $this;
  302. }
  303. $this->like .= $field . ' LIKE ? ';
  304. return $this;
  305. }
  306.  
  307.  
  308. public function between($field, $value1 = NULL, $value2 = NULL, $concatenator = NULL){
  309. if(empty($concatenator)){
  310. $concatenator = "";
  311. }
  312. $this->between .= " ". $concatenator . " " .$field . " BETWEEN " . $value1 . " AND " . $value2 . " ";
  313. return $this;
  314. }
  315. /*
  316. public function andBetween($field, $value1 = NULL, $value2 = NULL){
  317. return $this->between($field, $value1, $value2, 'AND');
  318. }*/
  319.  
  320.  
  321. /**
  322. * Add a where clause to the query.
  323. * @param string $field The column to wich this clause applies.
  324. * @param mixed $value [optional]
  325. * <p>The value to compare the column with.</p>
  326. * <p>Leave this parameter and the operator parameter blank (NULL) to have the "IS NULL" operator (WHERE column IS NULL).</p>
  327. * <p>If this parameter is an array and no operator is given the "IN" operator will be used (WHERE column IN (value1, value2).</p>
  328. * <p>If this parameter is an array you can also specify the "NOT IN" operator as the next parameter (WHERE column NOT IN (value1, value2).</p>
  329. * <p>If this parameter is a string and no operator is given the "=" operator will be used (WHERE column = value).</p>
  330. * @param string $operator [optional] <p>The operator that will be used (e.g. "IS NULL", "IN", "NOT IN", "=", "<>", ...).</p>
  331. * @param string $concatenator [optional] <p>Leave empty if this is the first where clause of the query.</p>
  332. * <p>Possible values "AND" and "OR". You can also use the andwhere and orwhere functions of this class.</p>
  333. * @return db
  334. */
  335. public function where($field, $value = NULL, $operator = NULL, $concatenator = NULL){
  336. if(empty($concatenator)){
  337. $concatenator = "";
  338. }
  339. $this->where .= $this->condition($field, $value, $operator, $concatenator);
  340. return $this;
  341. }
  342.  
  343.  
  344.  
  345. /**
  346. * Add a "and where" clause to the query.
  347. * @param string $field The column to wich this clause applies.
  348. * @param mixed $value [optional]
  349. * <p>The value to compare the column with.</p>
  350. * <p>Leave this parameter and the operator parameter blank (NULL) to have the "IS NULL" operator (WHERE column IS NULL).</p>
  351. * <p>If this parameter is an array and no operator is given the "IN" operator will be used (WHERE column IN (value1, value2).</p>
  352. * <p>If this parameter is an array you can also specify the "NOT IN" operator as the next parameter (WHERE column NOT IN (value1, value2).</p>
  353. * <p>If this parameter is a string and no operator is given the "=" operator will be used (WHERE column = value).</p>
  354. * @param string $operator [optional] <p>The operator that will be used (e.g. "IS NULL", "IN", "NOT IN", "=", "<>", ...).</p>
  355. * @return db
  356. */
  357. public function andwhere($field, $value = NULL, $operator = NULL){
  358. return $this->where($field, $value, $operator, " AND ");
  359. }
  360.  
  361. /**
  362. * Add a "or where" clause to the query.
  363. * @param string $field The column to wich this clause applies.
  364. * @param mixed $value [optional]
  365. * <p>The value to compare the column with.</p>
  366. * <p>Leave this parameter and the operator parameter blank (NULL) to have the "IS NULL" operator (WHERE column IS NULL).</p>
  367. * <p>If this parameter is an array and no operator is given the "IN" operator will be used (WHERE column IN (value1, value2).</p>
  368. * <p>If this parameter is an array you can also specify the "NOT IN" operator as the next parameter (WHERE column NOT IN (value1, value2).</p>
  369. * <p>If this parameter is a string and no operator is given the "=" operator will be used (WHERE column = value).</p>
  370. * @param string $operator [optional] <p>The operator that will be used (e.g. "IS NULL", "IN", "NOT IN", "=", "<>", ...).</p>
  371. * @return db
  372. */
  373. public function orwhere($field, $value = NULL, $operator = NULL){
  374. return $this->where($field, $value, $operator, "OR");
  375. }
  376.  
  377.  
  378. /**
  379. * Add a group by clause to the query.
  380. * @param mixed $fields A string containing the comma-separated columns (or a single column name) or an array containing the columns (or a single column).
  381. * @return db
  382. */
  383. public function groupby($fields){
  384. if(!is_array($fields)){
  385. $fields = array($fields);
  386. }
  387. foreach($fields as $f){
  388. if(!empty($this->groupby)){
  389. $this->groupby .= ", " . $f;
  390. }
  391. else {
  392. $this->groupby = $f;
  393. }
  394. }
  395. return $this;
  396. }
  397.  
  398. /**
  399. * Add a having clause to the query.
  400. * @param string $field The column to wich this clause applies.
  401. * @param mixed $value [optional]
  402. * <p>The value to compare the column with.</p>
  403. * <p>Leave this parameter and the operator parameter blank (NULL) to have the "IS NULL" operator (HAVING column IS NULL).</p>
  404. * <p>If this parameter is an array and no operator is given the "IN" operator will be used (HAVING column IN (value1, value2).</p>
  405. * <p>If this parameter is an array you can also specify the "NOT IN" operator as the next parameter (HAVING column IN (value1, value2).</p>
  406. * <p>If this parameter is a string and no operator is given the "=" operator will be used (HAVING column = value).</p>
  407. * @param string $operator [optional] <p>The operator that will be used (e.g. "IS NULL", "IN", "NOT IN", "=", "<>", ...).</p>
  408. * @param string $concatenator [optional] <p>Leave empty if this is the first having clause of the query.</p>
  409. * <p>Possible values "AND" and "OR". You can also use the andhaving and orhaving functions of this class.</p>
  410. * @return db
  411. */
  412. public function having($field, $value = NULL, $operator = NULL, $concatenator = NULL){
  413. if(empty($concatenator)){
  414. $concatenator = "";
  415. }
  416. $this->having .= $this->condition($field, $value, $operator, $concatenator);
  417. return $this;
  418. }
  419.  
  420. /**
  421. * Add a "and having" clause to the query.
  422. * @param string $field The column to wich this clause applies.
  423. * @param mixed $value [optional]
  424. * <p>The value to compare the column with.</p>
  425. * <p>Leave this parameter and the operator parameter blank (NULL) to have the "IS NULL" operator (HAVING column IS NULL).</p>
  426. * <p>If this parameter is an array and no operator is given the "IN" operator will be used (HAVING column IN (value1, value2).</p>
  427. * <p>If this parameter is an array you can also specify the "NOT IN" operator as the next parameter (HAVING column IN (value1, value2).</p>
  428. * <p>If this parameter is a string and no operator is given the "=" operator will be used (HAVING column = value).</p>
  429. * @param string $operator [optional] <p>The operator that will be used (e.g. "IS NULL", "IN", "NOT IN", "=", "<>", ...).</p>
  430. * @return db
  431. */
  432. public function andhaving($field, $value = NULL, $operator = NULL){
  433. return $this->having($field, $value, $operator, "AND");
  434. }
  435.  
  436. /**
  437. * Add a "or having" clause to the query.
  438. * @param string $field The column to wich this clause applies.
  439. * @param mixed $value [optional]
  440. * <p>The value to compare the column with.</p>
  441. * <p>Leave this parameter and the operator parameter blank (NULL) to have the "IS NULL" operator (HAVING column IS NULL).</p>
  442. * <p>If this parameter is an array and no operator is given the "IN" operator will be used (HAVING column IN (value1, value2).</p>
  443. * <p>If this parameter is an array you can also specify the "NOT IN" operator as the next parameter (HAVING column IN (value1, value2).</p>
  444. * <p>If this parameter is a string and no operator is given the "=" operator will be used (HAVING column = value).</p>
  445. * @param string $operator [optional] <p>The operator that will be used (e.g. "IS NULL", "IN", "NOT IN", "=", "<>", ...).</p>
  446. * @return db
  447. */
  448. public function orhaving($field, $value = NULL, $operator = NULL){
  449. return $this->having($field, $value, $operator, "OR");
  450. }
  451.  
  452. /**
  453. * Add an order by clause to the query.
  454. * @param mixed $fields A string containing the comma-separated columns (or a single column name) or an array containing the columns (or a single column).
  455. * @param string $order [optional] <p>"ASC" or "DESC"</p>.
  456. * @return db
  457. */
  458. public function orderby($fields, $order = NULL){
  459. if(empty($order)){
  460. $order = "ASC";
  461. }
  462. if(!is_array($fields)){
  463. $fields = array($fields);
  464. }
  465. foreach($fields as $f){
  466. $f = $f . " " . $order;
  467. if(!empty($this->orderby)){
  468. $this->orderby .= ", " . $f;
  469. }
  470. else {
  471. $this->orderby = $f;
  472. }
  473. }
  474. return $this;
  475. }
  476.  
  477. /**
  478. * Add a limit clause to the query.
  479. * @param Integer $limit
  480. * @param Integer $range
  481. * @return db
  482. */
  483. public function limit($limit, $range=NULL){
  484. if(empty($range) || $this->type == 'update' || $this->type == 'delete'){
  485. if(is_numeric($limit)){
  486. $this->limit = $limit;
  487. }
  488. }
  489. else{
  490. if(is_numeric($limit) && is_numeric($range)){
  491. $this->limit = $limit . ', ' . $range;
  492. }
  493.  
  494. }
  495. return $this;
  496. }
  497.  
  498. /**
  499. * If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed.
  500. * @param array $fields An array with the column names as key and the the values they should update to as values.
  501. * @return db
  502. */
  503. public function on_duplicate_key_update(array $fields){
  504. $f = array_keys($fields);
  505. $bind = array();
  506. foreach($f as $field) {
  507. $key = str_replace('.', '', $field);
  508. $i = 0;
  509. while(isset($this->bind[":$key"])){
  510. $i++;
  511. $key = str_replace('.', '', $field) . $i;
  512. }
  513. $bind[":$key"] = $fields[$field];
  514. $this->on_duplicate .= $field . ' = :' . $key . ', ';
  515. }
  516. $this->on_duplicate = substr($this->on_duplicate, 0, -2);
  517. $this->bind += $this->cleanup($bind);
  518. return $this;
  519. }
  520.  
  521. /**
  522. * Execute the query.
  523. * @return mixed
  524. * Returns false on failure, returns a dbStatement on succes.
  525. */
  526. public function run($arr = NULL) {
  527. if(empty($this->sql)){
  528. $this->build();
  529. }
  530. $this->sql = trim($this->sql);
  531. $this->bind = $this->cleanup($this->bind);
  532. $this->error = "";
  533.  
  534. try {
  535. $stmt =$this->prepare($this->sql);
  536. foreach($this->bind as $bind => $value){
  537. switch (gettype($value)){
  538. case 'integer':
  539. $type = PDO::PARAM_INT;
  540. $value = (integer)$value;
  541. break;
  542. case 'string':
  543. $type = PDO::PARAM_STR;
  544. $value = (string)$value;
  545. break;
  546. case 'boolean':
  547. $type = PDO::PARAM_BOOL;
  548. $value = (boolean)$value;
  549. break;
  550. case 'NULL':
  551. $type = PDO::PARAM_NULL;
  552. break;
  553. default:
  554. NULL;
  555. break;
  556. }
  557. $stmt->bindValue($bind, $value, $type);
  558. }
  559. if($stmt->execute($arr) !== false) {
  560. return $stmt;
  561. }
  562. } catch (PDOException $e) {
  563. print $e->getMessage();
  564. $this->error = $e->getMessage();
  565. $this->debug();
  566. return false;
  567. }
  568. }
  569.  
  570. /**
  571. * Build the query. If this is not executed before the run() method, it will be called by that method.
  572. * @return db
  573. */
  574. public function build(){
  575. switch ($this->type) {
  576.  
  577. case 'select':
  578. if(is_array($this->fields)){
  579. if(empty($this->fields)){
  580. $this->fields = array("*");
  581. }
  582. $this->fields = implode($this->fields, ", ");
  583. }
  584. $this->sql = "SELECT " . $this->fields . " FROM " . $this->table;
  585. if(!empty($this->alias)){
  586. $this->sql .= " " . $this->alias;
  587. }
  588. if(!empty($this->jointables)){
  589. foreach($this->jointables as $table){
  590. $this->sql .= " " . $table['join type'] . " JOIN " . $table['table'] . " " . $table['alias'] . " ON (" . $table['condition'] . ")";
  591. }
  592. }
  593. if (!empty($this->like)){
  594. $this->sql .= " WHERE " . $this->like;
  595. }
  596. if (!empty($this->where)){
  597. $this->sql .= " WHERE " . $this->where;
  598. }
  599. if (!empty($this->between)){
  600. $this->sql .= $this->between;
  601. }
  602. if(!empty($this->groupby)){
  603. $this->sql .= " GROUP BY " . $this->groupby;
  604. }
  605. if(!empty($this->having)){
  606. $this->sql .= " HAVING " . $this->having;
  607. }
  608. if(!empty($this->orderby)){
  609. $this->sql .= " ORDER BY " . $this->orderby;
  610. }
  611. if(!empty($this->limit)){
  612. $this->sql .= " LIMIT " . $this->limit;
  613. }
  614. $this->sql .= ';';
  615. break;
  616.  
  617. case 'update':
  618. $this->sql = "UPDATE " . $this->table . " SET";
  619. foreach($this->fields as $f){
  620. $this->sql .= " " . $f . '= :' . $f . ",";
  621. }
  622. $this->sql = substr($this->sql, 0, -1);
  623. if (!empty($this->where)){
  624. $this->sql .= " WHERE " . $this->where;
  625. }
  626. if(!empty($this->orderby)){
  627. $this->sql .= " ORDER BY " . $this->orderby;
  628. }
  629. if(!empty($this->limit)){
  630. $this->sql .= " LIMIT " . $this->limit;
  631. }
  632. $this->sql .= ';';
  633. break;
  634.  
  635. case 'insert':
  636. $this->sql = "INSERT INTO " . $this->table . " (" . implode($this->fields, ", ") . ") VALUES (:" . implode($this->fields, ", :") . ")";
  637. if(!empty($this->on_duplicate)){
  638. $this->sql .= " ON DUPLICATE KEY UPDATE " . $this->on_duplicate;
  639. }
  640. $this->sql .= ';';
  641. break;
  642.  
  643. case 'delete':
  644. $this->sql = "DELETE FROM " . $this->table;
  645. if (!empty($this->where)){
  646. $this->sql .= " WHERE " . $this->where;
  647. }
  648. if(!empty($this->orderby)){
  649. $this->sql .= " ORDER BY " . $this->orderby;
  650. }
  651. if(!empty($this->limit)){
  652. $this->sql .= " LIMIT " . $this->limit;
  653. }
  654. $this->sql .= ';';
  655. break;
  656.  
  657. default:
  658. break;
  659.  
  660. }
  661. return $this;
  662. }
  663.  
  664. /**
  665. * Set the callback function and format to show errors (e.g. "print", "echo", ...).
  666. * @param string $errorCallbackFunction The callback function.
  667. * @param string $errorMsgFormat The format to display errors in ("html" or "text").
  668. * @return db
  669. */
  670. public function setErrorCallbackFunction($errorCallbackFunction, $errorMsgFormat=NULL) {
  671. if(empty($errorMsgFormat)){
  672. $errorMsgFormat = "html";
  673. }
  674. //Variable functions for won't work with language constructs such as echo and print, so these are replaced with print_r.
  675. if(in_array(strtolower($errorCallbackFunction), array("echo", "print"))){
  676. $errorCallbackFunction = "print_r";
  677. }
  678.  
  679. if(function_exists($errorCallbackFunction)) {
  680. $this->errorCallbackFunction = $errorCallbackFunction;
  681. if(!in_array(strtolower($errorMsgFormat), array("html", "text"))){
  682. $errorMsgFormat = "html";
  683. }
  684. $this->errorMsgFormat = $errorMsgFormat;
  685. }
  686. return $this;
  687. }
  688.  
  689. /**
  690. * Helper function for all the where and having functions of this class.
  691. * @param string $field The column to wich this clause applies.
  692. * @param mixed $value [optional]
  693. * <p>The value to compare the column with.</p>
  694. * <p>Leave this parameter and the operator parameter blank (NULL) to have the "IS NULL" operator.</p>
  695. * <p>If this parameter is an array and no operator is given the "IN" operator will be used.</p>
  696. * <p>If this parameter is an array you can also specify the "NOT IN" operator as the next parameter.</p>
  697. * <p>If this parameter is a string and no operator is given the "=" operator will be used.</p>
  698. * @param string $operator [optional] <p>The operator that will be used (e.g. "IS NULL", "IN", "NOT IN", "=", "<>", ...).</p>
  699. * @return string
  700. * A condition build based on the given parameters.
  701. */
  702. private function condition($field, $value, $oper, $concatenator){
  703.  
  704. if (!isset($oper) || $oper == "IN" || $oper == "NOT IN") {
  705. if (is_array($value)) {
  706. if(!isset($oper)){
  707. $operator = 'IN';
  708. }
  709. $v = '(';
  710. $i=0;
  711. foreach($value as $val){
  712. $i++;
  713. $v .= ':' . $field . $i . ', ';
  714. $bind[':' . $field . $i] = $val;
  715. }
  716. $v = substr($v, 0, -2);
  717. $v .= ')';
  718. $placeholder = $v;
  719. }
  720. elseif (!isset($value)) {
  721. $operator = 'IS NULL';
  722. }
  723. else {
  724. $operator = '=';
  725. }
  726. }
  727.  
  728. if(isset($oper)){
  729. if($oper == "IS NOT NULL"){
  730. $operator = 'IS NOT NULL';
  731. }
  732. else
  733. $operator = $oper;
  734. }
  735.  
  736.  
  737. if(isset($value)){
  738. if(!isset($placeholder)){
  739. $placeholder = ':' . $field;
  740. $placeholder = str_replace('.', '', $placeholder);
  741. $i = 0;
  742. while(isset($this->bind[$placeholder])){
  743. $i++;
  744. $placeholder = ':' . $field . $i;
  745. $placeholder = str_replace('.', '', $placeholder);
  746. }
  747. $bind[$placeholder] = $value;
  748. }
  749.  
  750. $this->bind += $bind;
  751. if(!empty($concatenator)){
  752. $concatenator = " " . trim($concatenator) . " ";
  753. }
  754. }
  755. else
  756. $placeholder = "";
  757. return $concatenator . $field . " " . $operator. " " . $placeholder;
  758. }
  759.  
  760. /**
  761. * Display the encountered errors.
  762. */
  763. private function debug() {
  764. if(!empty($this->errorCallbackFunction)) {
  765. $error = array("Error" => $this->error);
  766. if(!empty($this->sql))
  767. $error["SQL Statement"] = $this->sql;
  768. if(!empty($this->bind))
  769. $error["Bind Parameters"] = trim(print_r($this->bind, true));
  770.  
  771. $backtrace = debug_backtrace();
  772. if(!empty($backtrace)) {
  773. foreach($backtrace as $info) {
  774. if($info["file"] != __FILE__)
  775. $error["Backtrace"] = $info["file"] . " at line " . $info["line"];
  776. }
  777. }
  778.  
  779. $msg = "";
  780. if($this->errorMsgFormat == "html") {
  781. if(!empty($error["Bind Parameters"]))
  782. $error["Bind Parameters"] = "<pre>" . $error["Bind Parameters"] . "</pre>";
  783. $css = trim(file_get_contents(dirname(__FILE__) . "/error.css"));
  784. $msg .= '<style type="text/css">' . "\n" . $css . "\n</style>";
  785. $msg .= "\n" . '<div class="db-error">' . "\n\t<h3>SQL Error</h3>";
  786. foreach($error as $key => $val)
  787. $msg .= "\n\t<label>" . $key . ":</label>" . $val;
  788. $msg .= "\n\t</div>\n</div>";
  789. }
  790. elseif($this->errorMsgFormat == "text") {
  791. $msg .= "SQL Error\n" . str_repeat("-", 50);
  792. foreach($error as $key => $val)
  793. $msg .= "\n\n$key:\n$val";
  794. }
  795.  
  796. $func = $this->errorCallbackFunction;
  797. $func($msg);
  798. }
  799. }
  800.  
  801. /**
  802. * Helper function to assure the data to bind is an array.
  803. * @param mixed $bind
  804. * @return Array
  805. */
  806. private function cleanup($bind) {
  807. if(!is_array($bind)) {
  808. if(!empty($bind))
  809. $bind = array($bind);
  810. else
  811. $bind = array();
  812. }
  813. return $bind;
  814. }
  815.  
  816. public function getSql()
  817. {
  818. return $this->sql;
  819. }
  820.  
  821. /**
  822. * Helper function to reset all fields before we start building a new query.
  823. */
  824. private function reset(){
  825. $this->error = NULL;
  826. $this->sql = NULL;
  827. $this->bind = array();
  828. $this->type = NULL;
  829. $this->table = NULL;
  830. $this->alias = NULL;
  831. $this->jointables = NULL;
  832. $this->fields = array();
  833. $this->where = "";
  834. $this->between = "";
  835. $this->like = "";
  836. $this->groupby = NULL;
  837. $this->having = "";
  838. $this->orderby = NULL;
  839. $this->limit = NULL;
  840. $this->on_duplicate = NULL;
  841. $this->stmt = NULL;
  842. }
  843.  
  844. public function __toString() {
  845. return '<pre>' . print_r($this, TRUE) . '</pre>';
  846. }
  847. /**
  848. *
  849. * $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
  850. public function getColumnNames($table){
  851. $sql = 'SHOW COLUMNS FROM ' . $table;
  852.  
  853. $stmt = $this->prepare($sql);
  854.  
  855. try {
  856. if($stmt->execute()){
  857. $raw_column_data = $stmt->fetchAll();
  858.  
  859. foreach($raw_column_data as $outer_key => $array){
  860. foreach($array as $inner_key => $value){
  861.  
  862. if ($inner_key === 'Field'){
  863. if (!(int)$inner_key){
  864. $column_names[] = $value;
  865. }
  866. }
  867. }
  868. }
  869. }
  870. return $column_names;
  871. } catch (Exception $e){
  872. return $e->getMessage(); //return exception
  873. }
  874. }
  875.  
  876. }
  877.  
  878. class dbStatement extends PDOStatement {
  879.  
  880. /**
  881. * Fetches the given field of next row from a result set.
  882. * @param mixed $fieldname The fieldname or a zero-based index for the field number.
  883. * @return mixed
  884. * The field value on succes, FALSE on failure
  885. */
  886. public function fetchField($fieldname = 0) {
  887. $data = $this->fetch(PDO::FETCH_BOTH);
  888. if(!isset($data[$fieldname])){
  889. $data[$fieldname] = FALSE;
  890. }
  891. return $data[$fieldname];
  892. }
  893.  
  894. /**
  895. * Fetches the next row from a result set as an associative array.
  896. * @return array
  897. * An associative array with the row data.
  898. */
  899. public function fetchAssoc() {
  900. return $this->fetch(PDO::FETCH_ASSOC);
  901. }
  902.  
  903. public function fetchAllAssoc(){
  904. return $this->fetchAll(PDO::FETCH_ASSOC);
  905. }
  906.  
  907. public function fetchTable($attributes = array()){
  908. $table = "<table";
  909. $table .= !empty($table_id) ? " id='$table_id'" : '';
  910. $table .= !empty($table_class) ? " class='$table_class'" : '';
  911. foreach($attributes as $attribute => $value){
  912. if(is_array($value)){
  913. //support multiple classes (e.g. class = "class1 class2").
  914. $value = implode(" ", $value);
  915. }
  916. $table .= " " . $attribute . "=\"" . $value . "\"";
  917. }
  918. $table .= ">\n";
  919. $tableheaders = "";
  920. $rows = "";
  921. $header = "";
  922. while($row = $this->fetchAssoc()){
  923. if(empty($tableheaders)){
  924. $header .= "\t<tr>\n";
  925. }
  926. $rows .= "\t<tr>\n";
  927. foreach ($row as $fieldname => $field){
  928. if(empty($tableheaders)){
  929. $header .= "\t\t<th>" . ucfirst(strtolower($fieldname)) . "</th>\n";
  930. }
  931. $rows .= "\t\t<td>" . $field . "</td>\n";
  932. }
  933. $rows .= "\t</tr>\n";
  934. if(empty ($tableheaders)){
  935. $header .= "\t</tr>\n";
  936. $tableheaders .= $header;
  937. }
  938. }
  939. $table .= $tableheaders . $rows . "</table>\n";
  940. return $table;
  941. }
  942. }
  943. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement