PageRenderTime 49ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/classes/mysql.class.php

https://github.com/magedeveloper/frosted-mysql-library
PHP | 1802 lines | 1608 code | 44 blank | 150 comment | 0 complexity | 62dbb9b0f7536b023c90c0e6f5860c95 MD5 | raw file
  1. <?php
  2. /**
  3. * Frosted MySQL Library Class
  4. * - - - - - - - - - -
  5. * Supplies different functions for fast and easy mysql communication. Build your
  6. * queries inside this class or fire direct queries and scalars. Works completely
  7. * without zend framework but delivers similar functionality. Build with php5 and
  8. * oop techniques to get best possible usability.
  9. * - - - - - - - - - -
  10. * If you include "mysqlClass_Config" class in your scripts, before the
  11. * communication class, you don't have to set up the class every time you use it.
  12. * Take a look at the example configuration file to get an overview.
  13. * - - - - - - - - - -
  14. * Licensed under MIT license
  15. * - - - - - - - - - -
  16. * @Creator Daniel 'Eisbehr' Kern
  17. * @Require PHP5
  18. * @Version 3.0
  19. * @Date 01.08.2013
  20. * @Update 01.08.2013
  21. * - - - - - - - - - -
  22. */
  23. class mysqlClass
  24. {
  25. /**
  26. * mysql hostname
  27. * @var string
  28. */
  29. private $hostname = "localhost";
  30. /**
  31. * mysql port number
  32. * @var string
  33. */
  34. private $port = "3306";
  35. /**
  36. * mysql username
  37. * @var string
  38. */
  39. private $username = "root";
  40. /**
  41. * password to access the database
  42. * @var string
  43. */
  44. private $password = "";
  45. /**
  46. * actually used database
  47. * @var string
  48. */
  49. private $database = "";
  50. /**
  51. * prefix for {PRE} or {PREFIX} replacement
  52. * @var string
  53. */
  54. private $prefix = "";
  55. /**
  56. * use a persistent mysql connection
  57. * @var boolean
  58. */
  59. private $persistent = true;
  60. /**
  61. * use mysqli instead of default mysql
  62. * @var boolean
  63. */
  64. private $mysqli = false;
  65. /**
  66. * selected connection type
  67. * @var string
  68. */
  69. private $type = self::CONNECTION_TYPE_WRITE;
  70. /*
  71. ** internal data fields
  72. */
  73. /**
  74. * actually database connection identifier
  75. * @var resource|mysqli
  76. */
  77. private $identifier;
  78. /**
  79. * last query result
  80. * @var mixed
  81. */
  82. private $result;
  83. /**
  84. * connection types for database handling
  85. * @var string array
  86. */
  87. private $types = array();
  88. /**
  89. * replace data inside of mysql queries
  90. * @var string array
  91. */
  92. private $replaces;
  93. /**
  94. * verbose on error
  95. * @var boolean
  96. */
  97. private $verbose = false;
  98. /**
  99. * verbose on error
  100. * @var boolean
  101. */
  102. private $format = false;
  103. /*
  104. ** query classes
  105. */
  106. /**
  107. * select query
  108. * @var mysqlClass_Select
  109. */
  110. private $querySelect = NULL;
  111. /**
  112. * insert query
  113. * @var mysqlClass_Insert
  114. */
  115. private $queryInsert = NULL;
  116. /**
  117. * replace query
  118. * @var mysqlClass_Replace
  119. */
  120. private $queryReplace = NULL;
  121. /**
  122. * update query
  123. * @var mysqlClass_Update
  124. */
  125. private $queryUpdate = NULL;
  126. /**
  127. * delete query
  128. * @var mysqlClass_Delete
  129. */
  130. private $queryDelete = NULL;
  131. /**
  132. * truncate query
  133. * @var mysqlClass_Truncate
  134. */
  135. private $queryTruncate = NULL;
  136. /*
  137. ** static & constants
  138. */
  139. /**
  140. * singleton instance holder
  141. * @var mysqlClass
  142. */
  143. private static $instance = NULL;
  144. /**
  145. * connection types
  146. * @var string
  147. */
  148. const CONNECTION_TYPE_READ = "r";
  149. const CONNECTION_TYPE_WRITE = "w";
  150. /**
  151. * result fetching types
  152. * @var string
  153. */
  154. const FETCH_ARRAY = "array";
  155. const FETCH_ASSOC = "assoc";
  156. const FETCH_ROW = "row";
  157. const FETCH_OBJ = "obj";
  158. const FETCH_OBJECT = "object";
  159. const FETCH_COLLECTION = "collection";
  160. /**
  161. * join condition relations
  162. * @var string
  163. */
  164. const JOIN_OR = "OR";
  165. const JOIN_AND = "AND";
  166. /**
  167. * where condition relations
  168. * @var string
  169. */
  170. const WHERE_OR = "OR";
  171. const WHERE_AND = "AND";
  172. /**
  173. * having condition relations
  174. * @var string
  175. */
  176. const HAVING_OR = "OR";
  177. const HAVING_AND = "AND";
  178. /**
  179. * group directions
  180. * @var string
  181. */
  182. const GROUP_ASC = "ASC";
  183. const GROUP_DESC = "DESC";
  184. /**
  185. * order directions
  186. * @var string
  187. */
  188. const ORDER_ASC = "ASC";
  189. const ORDER_DESC = "DESC";
  190. /**
  191. * exception messages
  192. * @var string
  193. */
  194. const MESSAGE_CONNECTION = "connection could not be established";
  195. const MESSAGE_DATABASE = "could not handle or get into the chosen database '%s'";
  196. const MESSAGE_QUERY = "could not process the given query";
  197. const MESSAGE_CREATE = "could not create the mysql query";
  198. const MESSAGE_PERMISSION = "the mysqlClass instance doesn't have the permission for this query, change the connection type to 'write' first";
  199. const MESSAGE_UNKNOWN = "function '%s(%s)' not found in class '%s'";
  200. /*
  201. ** constuct & destruct
  202. */
  203. /**
  204. * create mysql class instance
  205. * @param boolean $verbose
  206. * @param string $type
  207. * @return mysqlClass
  208. */
  209. function __construct($verbose = false, $type = self::CONNECTION_TYPE_WRITE)
  210. {
  211. // reset class configuration
  212. $this->resetConfig();
  213. // create connection types
  214. $this->types["r"] = self::CONNECTION_TYPE_READ;
  215. $this->types["read"] = self::CONNECTION_TYPE_READ;
  216. $this->types["w"] = self::CONNECTION_TYPE_WRITE;
  217. $this->types["write"] = self::CONNECTION_TYPE_WRITE;
  218. // check if chosen type exists
  219. if( array_key_exists($type, $this->types) )
  220. $this->type = $this->types[$type];
  221. else
  222. $this->type = self::CONNECTION_TYPE_WRITE;
  223. // get verbose option
  224. if( is_bool($verbose) ) $this->verbose = $verbose;
  225. // try to find config class
  226. if( class_exists("mysqlClass_Config") )
  227. {
  228. $class = new ReflectionClass("mysqlClass_Config");
  229. // get possible configuration from config class
  230. if( $class->hasConstant("hostname") ) $this->hostname = mysqlClass_Config::hostname;
  231. if( $class->hasConstant("port") ) $this->port = mysqlClass_Config::port;
  232. if( $class->hasConstant("username") ) $this->username = mysqlClass_Config::username;
  233. if( $class->hasConstant("password") ) $this->password = mysqlClass_Config::password;
  234. if( $class->hasConstant("database") ) $this->database = mysqlClass_Config::database;
  235. if( $class->hasConstant("prefix") ) $this->prefix = mysqlClass_Config::prefix;
  236. if( $class->hasConstant("persistent") ) $this->persistent = mysqlClass_Config::persistent;
  237. if( $class->hasConstant("mysqli") ) $this->mysqli = mysqlClass_Config::mysqli;
  238. if( $class->hasConstant("verbose") ) $this->verbose = mysqlClass_Config::verbose;
  239. if( $class->hasConstant("format") ) $this->format = mysqlClass_Config::format;
  240. }
  241. // create default data replacement
  242. $this->updateReplacement();
  243. // set singleton class instance
  244. self::$instance = $this;
  245. return $this;
  246. }
  247. /**
  248. * destruct mysql class instance
  249. * @return boolean
  250. */
  251. function __destruct()
  252. {
  253. $this->close();
  254. self::$instance = NULL;
  255. unset($this->identifier);
  256. unset($this->result);
  257. unset($this);
  258. return true;
  259. }
  260. /**
  261. * return class singleton or create new instance
  262. * @param boolean $forceNew
  263. * @return mysqlClass
  264. */
  265. public static function getInstance($forceNew = false)
  266. {
  267. if( $forceNew ) return new self();
  268. if( !self::$instance ) self::$instance = new self();
  269. return self::$instance;
  270. }
  271. /*
  272. ** getter & setter for internal data
  273. */
  274. /**
  275. * handle all get calls
  276. * @param string $name
  277. * @return mixed
  278. */
  279. public function getData($name)
  280. {
  281. switch( $name )
  282. {
  283. case "hostname":
  284. case "port":
  285. case "username":
  286. case "password":
  287. case "database":
  288. case "prefix":
  289. case "type":
  290. case "connectiontype":
  291. return (string)$this->{$name};
  292. break;
  293. case "connection":
  294. case "identifier":
  295. return $this->identifier;
  296. break;
  297. case "verbose":
  298. case "format":
  299. case "persistent":
  300. case "mysqli":
  301. return (bool)$this->{$name};
  302. break;
  303. }
  304. $this->unknownFunction($this, $name);
  305. return NULL;
  306. }
  307. /**
  308. * mysql hostname
  309. * @return string
  310. */
  311. public function getHostname()
  312. {
  313. return $this->getData("hostname");
  314. }
  315. /**
  316. * set mysql port number
  317. * @return string|integer
  318. */
  319. public function getPort()
  320. {
  321. return $this->getData("port");
  322. }
  323. /**
  324. * database username
  325. * @return string
  326. */
  327. public function getUsername()
  328. {
  329. return $this->getData("username");
  330. }
  331. /**
  332. * database password
  333. * @return string
  334. */
  335. public function getPassword()
  336. {
  337. return $this->getData("password");
  338. }
  339. /**
  340. * mysql database
  341. * @return string
  342. */
  343. public function getDatabase()
  344. {
  345. return $this->getData("database");
  346. }
  347. /**
  348. * database table prefix
  349. * @return string
  350. */
  351. public function getPrefix()
  352. {
  353. return $this->getData("prefix");
  354. }
  355. /**
  356. * persistent connection enabled
  357. * @return boolean
  358. */
  359. public function getPersistent()
  360. {
  361. return $this->getData("persistent");
  362. }
  363. /**
  364. * mysqli enabled
  365. * @return boolean
  366. */
  367. public function getMysqli()
  368. {
  369. return $this->getData("mysqli");
  370. }
  371. /**
  372. * verbose on error enabled
  373. * @return boolean
  374. */
  375. public function getVerbose()
  376. {
  377. return $this->getData("verbose");
  378. }
  379. /**
  380. * query string formation enabled
  381. * @return boolean
  382. */
  383. public function getFormat()
  384. {
  385. return $this->getData("format");
  386. }
  387. /**
  388. * set mysql connection type
  389. * @return boolean
  390. */
  391. public function getType()
  392. {
  393. return $this->getData("type");
  394. }
  395. /**
  396. * handle all set calls
  397. * @param string $name
  398. * @param mixed $value
  399. * @return boolean
  400. */
  401. public function setData($name, $value)
  402. {
  403. switch( $name )
  404. {
  405. case "hostname":
  406. case "username":
  407. case "password":
  408. if( is_string($value) )
  409. {
  410. $this->{$name} = $value;
  411. return true;
  412. }
  413. return false;
  414. break;
  415. case "database":
  416. case "prefix":
  417. if( is_string($value) )
  418. {
  419. $this->{$name} = $value;
  420. $this->updateReplacement();
  421. return true;
  422. }
  423. return false;
  424. break;
  425. case "port":
  426. if( is_string($value) || is_integer($value) )
  427. {
  428. $this->{$name} = $value;
  429. return true;
  430. }
  431. return false;
  432. break;
  433. case "verbose":
  434. case "format":
  435. case "persistent":
  436. case "mysqli":
  437. if( is_bool($value) )
  438. {
  439. $this->{$name} = $value;
  440. return true;
  441. }
  442. return false;
  443. break;
  444. case "type":
  445. case "connectiontype":
  446. if( array_key_exists($value, $this->types) )
  447. {
  448. $this->type = $this->types[$value];
  449. return true;
  450. }
  451. return false;
  452. break;
  453. }
  454. $this->unknownFunction($this, $name, array($value));
  455. return false;
  456. }
  457. /**
  458. * set mysql hostname
  459. * @param string $hostname
  460. * @return boolean
  461. */
  462. public function setHostname($hostname)
  463. {
  464. return $this->setData("hostname", $hostname);
  465. }
  466. /**
  467. * set mysql port number
  468. * @param string|integer $port
  469. * @return boolean
  470. */
  471. public function setPort($port)
  472. {
  473. return $this->setData("port", $port);
  474. }
  475. /**
  476. * set database username
  477. * @param string $username
  478. * @return boolean
  479. */
  480. public function setUsername($username)
  481. {
  482. return $this->setData("username", $username);
  483. }
  484. /**
  485. * set database password
  486. * @param string $password
  487. * @return boolean
  488. */
  489. public function setPassword($password)
  490. {
  491. return $this->setData("password", $password);
  492. }
  493. /**
  494. * set mysql database
  495. * @param string $database
  496. * @return boolean
  497. */
  498. public function setDatabase($database)
  499. {
  500. return $this->setData("database", $database);
  501. }
  502. /**
  503. * set database table prefix
  504. * @param string $prefix
  505. * @return boolean
  506. */
  507. public function setPrefix($prefix)
  508. {
  509. return $this->setData("prefix", $prefix);
  510. }
  511. /**
  512. * enable persistent connection
  513. * @param boolean $persistent
  514. * @return boolean
  515. */
  516. public function setPersistent($persistent)
  517. {
  518. return $this->setData("persistent", $persistent);
  519. }
  520. /**
  521. * enable mysqli
  522. * @param boolean $mysqli
  523. * @return boolean
  524. */
  525. public function setMysqli($mysqli)
  526. {
  527. return $this->setData("mysqli", $mysqli);
  528. }
  529. /**
  530. * enable verbose on error
  531. * @param boolean $verbose
  532. * @return boolean
  533. */
  534. public function setVerbose($verbose)
  535. {
  536. return $this->setData("verbose", $verbose);
  537. }
  538. /**
  539. * enable query string formation
  540. * @param boolean $format
  541. * @return boolean
  542. */
  543. public function setFormat($format)
  544. {
  545. return $this->setData("format", $format);
  546. }
  547. /**
  548. * set mysql connection type
  549. * @param string $type
  550. * @return boolean
  551. */
  552. public function setType($type)
  553. {
  554. return $this->setData("type", $type);
  555. }
  556. /**
  557. * set mysql connection type
  558. * @param string $connectiontype
  559. * @return boolean
  560. */
  561. public function setConnectionType($connectiontype)
  562. {
  563. return $this->setData("connectiontype", $connectiontype);
  564. }
  565. /**
  566. * get class configuration as array
  567. * @return array
  568. */
  569. public function getConfigArray()
  570. {
  571. $config = array();
  572. $config["hostname"] = $this->hostname;
  573. $config["port"] = $this->port;
  574. $config["username"] = $this->username;
  575. $config["password"] = $this->password;
  576. $config["database"] = $this->database;
  577. $config["prefix"] = $this->prefix;
  578. $config["persistent"] = $this->persistent;
  579. $config["mysqli"] = $this->mysqli;
  580. $config["verbose"] = $this->verbose;
  581. $config["format"] = $this->format;
  582. return $config;
  583. }
  584. /**
  585. * set class configuration as array
  586. * @param array $config
  587. * @return mysqlClass
  588. */
  589. public function setConfigArray($config)
  590. {
  591. if( isset($config["hostname"]) ) $this->hostname = $config["hostname"];
  592. if( isset($config["port"]) ) $this->port = $config["port"];
  593. if( isset($config["username"]) ) $this->username = $config["username"];
  594. if( isset($config["password"]) ) $this->password = $config["password"];
  595. if( isset($config["database"]) ) $this->database = $config["database"];
  596. if( isset($config["prefix"]) ) $this->prefix = $config["prefix"];
  597. if( isset($config["persistent"]) ) $this->persistent = $config["persistent"];
  598. if( isset($config["mysqli"]) ) $this->mysqli = $config["mysqli"];
  599. if( isset($config["verbose"]) ) $this->verbose = $config["verbose"];
  600. if( isset($config["format"]) ) $this->format = $config["format"];
  601. return $this;
  602. }
  603. /**
  604. * reset whole class configuration
  605. * @return void
  606. */
  607. public function resetConfig()
  608. {
  609. $this->close();
  610. $this->hostname = "localhost";
  611. $this->port = "3306";
  612. $this->username = "root";
  613. $this->password = "";
  614. $this->database = "";
  615. $this->prefix = "";
  616. $this->persistent = true;
  617. $this->mysqli = false;
  618. $this->verbose = false;
  619. $this->format = false;
  620. $this->updateReplacement();
  621. return;
  622. }
  623. /**
  624. * internal getter for mysql hostname by current configuration
  625. * @return string
  626. */
  627. private function getConnectionHostname()
  628. {
  629. if( $this->mysqli )
  630. {
  631. $hostname = ( $this->persistent ? "p:" : NULL) . $this->hostname;
  632. $hostname .= !empty($this->port) && (string)$this->port != "3306" ? ":" . $this->port : NULL;
  633. return $hostname;
  634. }
  635. $hostname = $this->hostname;
  636. $hostname .= !empty($this->port) && (string)$this->port != "3306" ? ":" . $this->port : NULL;
  637. return $hostname;
  638. }
  639. /*
  640. ** replacement functions
  641. */
  642. /**
  643. * replace all data inside mysql query
  644. * @param string $query
  645. * @return string
  646. */
  647. public function replaceQuery($query)
  648. {
  649. if( !is_array($this->replaces) ) $this->replaces = array();
  650. foreach( $this->replaces as $replace => $value )
  651. {
  652. $query = str_replace($replace, $value, $query);
  653. }
  654. return $query;
  655. }
  656. /**
  657. * reset replacements to default
  658. * @return void
  659. */
  660. private function updateReplacement()
  661. {
  662. if( !is_array($this->replaces) ) $this->replaces = array();
  663. $this->replaces["{DB}"] = $this->database;
  664. $this->replaces["{DATABASE}"] = $this->database;
  665. $this->replaces["{PRE}"] = $this->prefix;
  666. $this->replaces["{PREFIX}"] = $this->prefix;
  667. return;
  668. }
  669. /**
  670. * add a new replacement entry
  671. * @param string $replace
  672. * @param string $value
  673. * @return boolean
  674. */
  675. public function addReplacement($replace, $value)
  676. {
  677. if( !is_array($this->replaces) ) $this->updateReplacement();
  678. if( !empty($replace) && $replace != $value )
  679. {
  680. $this->replaces[$replace] = $value;
  681. return true;
  682. }
  683. return false;
  684. }
  685. /**
  686. * remove a single replacement
  687. * @param string $replace
  688. * @return void
  689. */
  690. public function removeReplacement($replace)
  691. {
  692. if( !is_array($this->replaces) ) $this->updateReplacement();
  693. if( isset($this->replaces[$replace]) )
  694. {
  695. unset($this->replaces[$replace]);
  696. }
  697. return;
  698. }
  699. /*
  700. ** connection related functions
  701. */
  702. /**
  703. * open connection to database
  704. * @return boolean
  705. */
  706. public function connect()
  707. {
  708. // close possible open connection
  709. $this->close();
  710. // use mysqli
  711. if( $this->mysqli )
  712. {
  713. if( $this->persistent )
  714. $this->identifier = mysqli_connect($this->getConnectionHostname(), $this->username, $this->password);
  715. else
  716. $this->identifier = mysqli_connect($this->getConnectionHostname(), $this->username, $this->password);
  717. // on connection error
  718. if( mysqli_connect_error() ) $this->connectionError();
  719. // select database
  720. if( @mysqli_select_db($this->identifier, $this->database) )
  721. return true;
  722. else
  723. $this->databaseError();
  724. }
  725. // use default mysql
  726. else
  727. {
  728. if( $this->persistent )
  729. $this->identifier = @mysql_connect($this->getConnectionHostname(), $this->username, $this->password, true);
  730. else
  731. $this->identifier = @mysql_pconnect($this->getConnectionHostname(), $this->username, $this->password);
  732. if( !$this->identifier && mysql_error() ) $this->connectionError();
  733. // if connection was successfully select database
  734. if( $this->identifier )
  735. {
  736. if( @mysql_select_db($this->database, $this->identifier) )
  737. return true;
  738. else
  739. $this->databaseError();
  740. }
  741. }
  742. return false;
  743. }
  744. /**
  745. * alias of connect()
  746. * @return boolean
  747. */
  748. public function reconnect()
  749. {
  750. return $this->connect();
  751. }
  752. /**
  753. * check if connection is established
  754. * @return boolean
  755. */
  756. public function isConnected()
  757. {
  758. if( $this->identifier )
  759. {
  760. if( $this->mysqli )
  761. {
  762. if( $this->identifier instanceof mysqli && mysqli_ping($this->identifier) )
  763. {
  764. return true;
  765. }
  766. }
  767. else
  768. {
  769. if( is_resource($this->identifier) && mysql_ping($this->identifier) )
  770. {
  771. return true;
  772. }
  773. }
  774. }
  775. return false;
  776. }
  777. /**
  778. * alias of isConnected()
  779. * @return boolean
  780. */
  781. public function ping()
  782. {
  783. return $this->isConnected();
  784. }
  785. /**
  786. * close mysql connection
  787. * @return boolean
  788. */
  789. public function close()
  790. {
  791. if( isset($this->identifyer) )
  792. {
  793. if( $this->mysqli )
  794. {
  795. if( $this->identifier instanceof mysqli )
  796. {
  797. @mysqli_close($this->identifier);
  798. return true;
  799. }
  800. }
  801. else
  802. {
  803. if( is_resource($this->identifier) )
  804. {
  805. @mysql_close($this->identifyer);
  806. return true;
  807. }
  808. }
  809. }
  810. return false;
  811. }
  812. /*
  813. ** query functions
  814. */
  815. /**
  816. * check if class has the permission for the query
  817. * @param string $query
  818. * @return boolean
  819. */
  820. private function hasQueryPermission($query)
  821. {
  822. if( $this->type == self::CONNECTION_TYPE_WRITE )
  823. return true;
  824. if( preg_match("/(INSERT|UPDATE|DELETE) (.*)/i", $query) ||
  825. preg_match("/(?:CREATE|DROP|ALTER|CACHE) (.*)(?:FUNCTION|TABLE|VIEW|EVENT|TRIGGER|INDEX|SERVER|USER|DATABASE|TABLESPACE|PROCEDURE) /i", $query) )
  826. return false;
  827. return true;
  828. }
  829. /**
  830. * run query string against database
  831. * @param string $query
  832. * @param boolean $fetch
  833. * @param string $fetchType
  834. * @return mixed
  835. */
  836. public function query($query, $fetch = false, $fetchType = self::FETCH_ASSOC)
  837. {
  838. // if query is not an empty string
  839. if( !empty($query) )
  840. {
  841. // replace data inside query
  842. $queryString = $this->replaceQuery($query);
  843. // check if query is allowed by given connection type
  844. if( $this->hasQueryPermission($queryString) )
  845. {
  846. // run mysqli query
  847. if( $this->mysqli )
  848. $this->result = @mysqli_query($this->identifier, $queryString);
  849. // run default query
  850. else
  851. $this->result = @mysql_query($queryString, $this->identifier);
  852. // return error on failed query
  853. if( !$this->result )
  854. $this->queryError();
  855. // fetch or return result
  856. else
  857. {
  858. // return fetched result
  859. if( $fetch )
  860. return $this->fetch($this->result, $fetchType);
  861. // return result
  862. return $this->result;
  863. }
  864. }
  865. else
  866. {
  867. // print permission error
  868. $this->permissionError();
  869. }
  870. }
  871. return false;
  872. }
  873. /**
  874. * alias of query()
  875. * @param string $query
  876. * @param boolean $fetch
  877. * @param string $fetchType
  878. * @return mixed
  879. */
  880. public function qry($query, $fetch = false, $fetchType = self::FETCH_ASSOC)
  881. {
  882. return $this->query($query, $fetch, $fetchType);
  883. }
  884. /**
  885. * affected rows by the last query
  886. * @return integer
  887. */
  888. public function getAffected()
  889. {
  890. if( $this->mysqli )
  891. {
  892. return mysqli_affected_rows($this->identifier);
  893. }
  894. return mysql_affected_rows($this->identifier);
  895. }
  896. /**
  897. * count the rows in the result
  898. * @return integer
  899. */
  900. public function getNumRows()
  901. {
  902. if( $this->mysqli )
  903. {
  904. return mysqli_num_rows($this->result);
  905. }
  906. return mysql_num_rows($this->result);
  907. }
  908. /**
  909. * get last insert id
  910. * @return integer
  911. */
  912. public function getLastId()
  913. {
  914. if( $this->mysqli )
  915. {
  916. return mysqli_insert_id($this->identifier);
  917. }
  918. if( ($id = @mysql_insert_id($this->identifier)) !== false )
  919. {
  920. return $id;
  921. }
  922. return 0;
  923. }
  924. /**
  925. * alias of getLastId()
  926. * @return integer | boolean
  927. */
  928. public function getLastInsertId()
  929. {
  930. return $this->getLastId();
  931. }
  932. /**
  933. * free result memory
  934. * @return boolean
  935. */
  936. public function free()
  937. {
  938. if( $this->mysqli )
  939. {
  940. mysqli_free_result($this->result);
  941. return true;
  942. }
  943. return @mysql_free_result($this->result);
  944. }
  945. /**
  946. * fetch result to useable formats
  947. * @param boolean|resource|mysqli_result $result
  948. * @param string $type
  949. * @return mixed
  950. */
  951. public function fetch($result = false, $type = "assoc")
  952. {
  953. // call again to shift parameters
  954. if( $result === false || is_string($result) )
  955. {
  956. $type = is_string($result) ? $result : $type;
  957. $fetched = $this->fetch($this->result, $type);
  958. $this->free();
  959. return $fetched;
  960. }
  961. $fetched = array();
  962. // array
  963. if( $type == self::FETCH_ARRAY )
  964. {
  965. if( $this->mysqli )
  966. while( $row = mysqli_fetch_array($result) )
  967. $fetched[] = $row;
  968. else
  969. while( $row = mysql_fetch_array($result) )
  970. $fetched[] = $row;
  971. return $fetched;
  972. }
  973. // row
  974. if( $type == self::FETCH_ROW )
  975. {
  976. if( $this->mysqli )
  977. while( $row = mysqli_fetch_row($result) )
  978. $fetched[] = $row;
  979. else
  980. while( $row = mysql_fetch_row($result) )
  981. $fetched[] = $row;
  982. return $fetched;
  983. }
  984. // object
  985. if( $type == self::FETCH_OBJ || $type == self::FETCH_OBJECT || $type == self::FETCH_COLLECTION )
  986. {
  987. $fetched = new mysqlClass_Collection();
  988. if( $this->mysqli )
  989. {
  990. while( $row = mysqli_fetch_assoc($result) )
  991. $fetched->addItem($fetched->getNewItemWithData($row));
  992. }
  993. else
  994. {
  995. while( $row = mysql_fetch_assoc($result) )
  996. $fetched->addItem($fetched->getNewItemWithData($row));
  997. }
  998. }
  999. // default / assoc
  1000. if( $this->mysqli )
  1001. while( $row = mysqli_fetch_assoc($result) )
  1002. $fetched[] = $row;
  1003. else
  1004. while( $row = mysql_fetch_assoc($result) )
  1005. $fetched[] = $row;
  1006. return $fetched;
  1007. }
  1008. /**
  1009. * fetch result to collection
  1010. * @param boolean|resource|mysqli_result $result
  1011. * @return mysqlClass_Collection
  1012. */
  1013. public function getCollection($result = false)
  1014. {
  1015. return $this->fetch($result, self::FETCH_COLLECTION);
  1016. }
  1017. /**
  1018. * escape and quote value inside mysql query
  1019. * @param string $value
  1020. * @param boolean $nullable
  1021. * @return string
  1022. */
  1023. public function escape($value, $nullable = true)
  1024. {
  1025. if( is_string($value) )
  1026. {
  1027. if( $this->mysqli )
  1028. {
  1029. if( $this->identifier instanceof mysqli )
  1030. $value = mysqli_real_escape_string($this->identifier, $value);
  1031. }
  1032. else
  1033. {
  1034. $value = mysql_real_escape_string($value);
  1035. }
  1036. }
  1037. if( is_null($value) && $nullable )
  1038. $value = "NULL";
  1039. elseif( is_numeric($value) );
  1040. // nothing to do, numeral literals need no escape
  1041. elseif( is_bool($value) )
  1042. $value = (integer)$value;
  1043. else
  1044. $value = "'" . $value . "'";
  1045. return $value;
  1046. }
  1047. /**
  1048. * alias of escape()
  1049. * @param string $value
  1050. * @param boolean $nullable
  1051. * @return string
  1052. */
  1053. public function e($value, $nullable = true)
  1054. {
  1055. return $this->escape($value, $nullable);
  1056. }
  1057. /**
  1058. * alias of escape()
  1059. * @param string $value
  1060. * @param boolean $nullable
  1061. * @return string
  1062. */
  1063. public function __($value, $nullable = true)
  1064. {
  1065. return $this->escape($value, $nullable);
  1066. }
  1067. /*
  1068. ** error verbose function
  1069. */
  1070. /**
  1071. * print connection error or throw exception on verbose
  1072. * otherwise die with an message
  1073. * @throws mysqlClass_Connection_Exception
  1074. * @return void
  1075. */
  1076. private function connectionError()
  1077. {
  1078. if( $this->verbose )
  1079. {
  1080. if( $this->mysqli )
  1081. $reason = mysqli_connect_error();
  1082. else
  1083. $reason = mysql_error($this->identifier);
  1084. throw new mysqlClass_Connection_Exception(self::MESSAGE_CONNECTION . ", reason: " . $reason);
  1085. }
  1086. $this->printError(self::MESSAGE_CONNECTION . "!");
  1087. }
  1088. /**
  1089. * print database error or throw exception on verbose
  1090. * @throws mysqlClass_Database_Exception
  1091. * @return void
  1092. */
  1093. private function databaseError()
  1094. {
  1095. $message = sprintf(self::MESSAGE_DATABASE, $this->database);
  1096. if( $this->verbose)
  1097. {
  1098. if( $this->mysqli )
  1099. $reason = mysqli_error($this->identifier);
  1100. else
  1101. $reason = mysql_error($this->identifier);
  1102. throw new mysqlClass_Database_Exception($message . ", reason: " . $reason);
  1103. }
  1104. $this->printError($message . " !");
  1105. }
  1106. /**
  1107. * print query error or throw exception on verbose
  1108. * @throws mysqlClass_Query_Exception
  1109. * @return void
  1110. */
  1111. private function queryError()
  1112. {
  1113. if( $this->verbose)
  1114. {
  1115. if( $this->mysqli )
  1116. $reason = mysqli_error($this->identifier);
  1117. else
  1118. $reason = mysql_error($this->identifier);
  1119. throw new mysqlClass_Query_Exception(self::MESSAGE_QUERY . ", reason: " . $reason);
  1120. }
  1121. $this->printError(self::MESSAGE_QUERY . "!");
  1122. }
  1123. /**
  1124. * print create error or throw exception on verbose
  1125. * @param string $reason
  1126. * @throws mysqlClass_Create_Exception
  1127. */
  1128. public function createError($reason = NULL)
  1129. {
  1130. if( $this->verbose)
  1131. {
  1132. if( !is_null($reason) )
  1133. throw new mysqlClass_Create_Exception(self::MESSAGE_CREATE . ", reason: " . strtolower($reason));
  1134. throw new mysqlClass_Create_Exception(self::MESSAGE_CREATE);
  1135. }
  1136. if( !is_null($reason) )
  1137. {
  1138. $this->printError(self::MESSAGE_CREATE . ", reason: " . strtolower($reason));
  1139. return;
  1140. }
  1141. $this->printError(self::MESSAGE_CREATE . "!");
  1142. }
  1143. /**
  1144. * print permission error or throw exception on verbose
  1145. * dies or throws an mysqlClass_Permission_Exception
  1146. * @throws mysqlClass_Permission_Exception
  1147. */
  1148. private function permissionError()
  1149. {
  1150. if( $this->verbose )
  1151. throw new mysqlClass_Permission_Exception(self::MESSAGE_PERMISSION);
  1152. $this->printError(self::MESSAGE_PERMISSION . "!");
  1153. }
  1154. /**
  1155. * print unknown function error or throw exception on verbose
  1156. * @param object $class
  1157. * @param string $name
  1158. * @param array $parameter
  1159. * @throws mysqlClass_Unknown_Function_Exception
  1160. */
  1161. public function unknownFunction($class, $name, $parameter = array())
  1162. {
  1163. $params = "";
  1164. for( $i = 1; $i <= count($parameter); $i++ )
  1165. {
  1166. $params .= "param" . $i;
  1167. if( $i != count($parameter) )
  1168. {
  1169. $params .= ", ";
  1170. }
  1171. }
  1172. $message = sprintf(self::MESSAGE_UNKNOWN, $name, $params, get_class($class));
  1173. if( $this->verbose)
  1174. throw new mysqlClass_Unknown_Function_Exception($message);
  1175. $this->printError($message . " !");
  1176. }
  1177. /**
  1178. * print a non-verbose message
  1179. * @param string $message
  1180. */
  1181. private function printError($message)
  1182. {
  1183. if( !$this->verbose )
  1184. {
  1185. trigger_error($message, E_USER_ERROR);
  1186. }
  1187. }
  1188. /*
  1189. ** query initializer
  1190. */
  1191. /**
  1192. * get select query instance
  1193. * @param string|array $columns
  1194. * @param boolean $newInstance
  1195. * @return mysqlClass_Select
  1196. */
  1197. public function select($columns = "*", $newInstance = false)
  1198. {
  1199. // prevent php debug notification
  1200. if( $columns && $newInstance );
  1201. $args = array();
  1202. // check if new instance have to be created
  1203. if( func_num_args() > 0 )
  1204. {
  1205. $args = func_get_args();
  1206. $last = array_splice($args, -1);
  1207. if( is_bool($last[0]) )
  1208. {
  1209. if( $last[0] )
  1210. {
  1211. $instance = new mysqlClass_Select($this);
  1212. if( !empty($args) )
  1213. call_user_func_array(array($instance, "columns"), $args);
  1214. return $instance;
  1215. }
  1216. }
  1217. else
  1218. {
  1219. array_push($args, $last);
  1220. }
  1221. }
  1222. // create instance or reset
  1223. if( !$this->querySelect )
  1224. $this->querySelect = new mysqlClass_Select($this);
  1225. else
  1226. $this->querySelect->resetQuery($this->format);
  1227. // pass parameter
  1228. if( count($args) > 0 )
  1229. call_user_func_array(array($this->querySelect, "columns"), $args);
  1230. return $this->querySelect;
  1231. }
  1232. /**
  1233. * get insert query instance
  1234. * @param string $table
  1235. * @param boolean $newInstance
  1236. * @return mysqlClass_Insert
  1237. */
  1238. public function insert($table = NULL, $newInstance = false)
  1239. {
  1240. // prevent php debug notification
  1241. if( $table && $newInstance );
  1242. $args = array();
  1243. // check parameters for new instance
  1244. if( func_num_args() > 0 )
  1245. {
  1246. // extract last parameter
  1247. $args = func_get_args();
  1248. $last = array_splice($args, -1);
  1249. // if last parameter is a boolean
  1250. if( is_bool($last[0]) )
  1251. {
  1252. // if new instance has to be created
  1253. if( $last[0] )
  1254. {
  1255. $instance = new mysqlClass_Insert($this);
  1256. if( !empty($args) )
  1257. call_user_func_array(array($instance, "table"), $args);
  1258. return $instance;
  1259. }
  1260. }
  1261. // otherwise push parameter back in list
  1262. else
  1263. {
  1264. array_push($args, $last);
  1265. }
  1266. }
  1267. // create instance or reset
  1268. if( !$this->queryInsert)
  1269. $this->queryInsert = new mysqlClass_Insert($this);
  1270. else
  1271. $this->queryInsert->resetQuery($this->format);
  1272. // pass parameter
  1273. if( count($args) > 0 )
  1274. call_user_func_array(array($this->queryInsert, "table"), $args);
  1275. return $this->queryInsert;
  1276. }
  1277. /**
  1278. * get insert query instance
  1279. * @param string $table
  1280. * @param boolean $newInstance
  1281. * @return mysqlClass_Insert
  1282. */
  1283. public function insertInto($table = NULL, $newInstance = false)
  1284. {
  1285. // prevent php debug notification
  1286. if( $table && $newInstance );
  1287. return call_user_func_array(array($this, "insert"), func_get_args());
  1288. }
  1289. /**
  1290. * get replace query instance
  1291. * @param string $table
  1292. * @param boolean $newInstance
  1293. * @return mysqlClass_Replace
  1294. */
  1295. public function replace($table = NULL, $newInstance = false)
  1296. {
  1297. // prevent php debug notification
  1298. if( $table && $newInstance );
  1299. $args = array();
  1300. // check parameters for new instance
  1301. if( func_num_args() > 0 )
  1302. {
  1303. // extract last parameter
  1304. $args = func_get_args();
  1305. $last = array_splice($args, -1);
  1306. // if last parameter is a boolean
  1307. if( is_bool($last[0]) )
  1308. {
  1309. // if new instance has to be created
  1310. if( $last[0] )
  1311. {
  1312. $instance = new mysqlClass_Replace($this);
  1313. if( !empty($args) )
  1314. call_user_func_array(array($instance, "table"), $args);
  1315. return $instance;
  1316. }
  1317. }
  1318. // otherwise push parameter back in list
  1319. else
  1320. {
  1321. array_push($args, $last);
  1322. }
  1323. }
  1324. // create instance or reset
  1325. if( !$this->queryReplace)
  1326. $this->queryReplace = new mysqlClass_Replace($this);
  1327. else
  1328. $this->queryReplace->resetQuery($this->format);
  1329. // pass parameter
  1330. if( count($args) > 0 )
  1331. call_user_func_array(array($this->queryReplace, "table"), $args);
  1332. return $this->queryReplace;
  1333. }
  1334. /**
  1335. * get replace query instance
  1336. * @param string $table
  1337. * @param boolean $newInstance
  1338. * @return mysqlClass_Replace
  1339. */
  1340. public function replaceInto($table = NULL, $newInstance = false)
  1341. {
  1342. // prevent php debug notification
  1343. if( $table && $newInstance );
  1344. return call_user_func_array(array($this, "replace"), func_get_args());
  1345. }
  1346. /**
  1347. * get update query instance
  1348. * @param string|array $table
  1349. * @param boolean $newInstance
  1350. * @return mysqlClass_Update
  1351. */
  1352. public function update($table = NULL, $newInstance = false)
  1353. {
  1354. // prevent php debug notification
  1355. if( $table && $newInstance );
  1356. $args = array();
  1357. // check parameters for new instance
  1358. if( func_num_args() > 0 )
  1359. {
  1360. // extract last parameter
  1361. $args = func_get_args();
  1362. $last = array_splice($args, -1);
  1363. // if last parameter is a boolean
  1364. if( is_bool($last[0]) )
  1365. {
  1366. // if new instance has to be created
  1367. if( $last[0] )
  1368. {
  1369. $instance = new mysqlClass_Update($this);
  1370. if( !empty($args) )
  1371. call_user_func_array(array($instance, "table"), $args);
  1372. return $instance;
  1373. }
  1374. }
  1375. // otherwise push parameter back in list
  1376. else
  1377. {
  1378. array_push($args, $last);
  1379. }
  1380. }
  1381. // create instance or reset
  1382. if( !$this->queryUpdate)
  1383. $this->queryUpdate = new mysqlClass_Update($this);
  1384. else
  1385. $this->queryUpdate->resetQuery($this->format);
  1386. // pass parameter
  1387. if( count($args) > 0 )
  1388. call_user_func_array(array($this->queryUpdate, "table"), $args);
  1389. return $this->queryUpdate;
  1390. }
  1391. /**
  1392. * get update query instance
  1393. * @param string|array $table
  1394. * @param boolean $newInstance
  1395. * @return mysqlClass_Delete
  1396. */
  1397. public function delete($table = NULL, $newInstance = false)
  1398. {
  1399. // prevent php debug notification
  1400. if( $table && $newInstance );
  1401. $args = array();
  1402. // check parameters for new instance
  1403. if( func_num_args() > 0 )
  1404. {
  1405. // extract last parameter
  1406. $args = func_get_args();
  1407. $last = array_splice($args, -1);
  1408. // if last parameter is a boolean
  1409. if( is_bool($last[0]) )
  1410. {
  1411. // if new instance has to be created
  1412. if( $last[0] )
  1413. {
  1414. $instance = new mysqlClass_Delete($this);
  1415. if( !empty($args) )
  1416. call_user_func_array(array($instance, "table"), $args);
  1417. return $instance;
  1418. }
  1419. }
  1420. // otherwise push parameter back in list
  1421. else
  1422. {
  1423. array_push($args, $last);
  1424. }
  1425. }
  1426. // create instance or reset
  1427. if( !$this->queryDelete)
  1428. $this->queryDelete = new mysqlClass_Delete($this);
  1429. else
  1430. $this->queryDelete->resetQuery($this->format);
  1431. // pass parameter
  1432. if( count($args) > 0 )
  1433. call_user_func_array(array($this->queryDelete, "table"), $args);
  1434. return $this->queryDelete;
  1435. }
  1436. /**
  1437. * get update query instance
  1438. * @param string|array $table
  1439. * @param boolean $newInstance
  1440. * @return mysqlClass_Delete
  1441. */
  1442. public function deleteFrom($table = NULL, $newInstance = false)
  1443. {
  1444. // prevent php debug notification
  1445. if( $table && $newInstance );
  1446. return call_user_func_array(array($this, "delete"), func_get_args());
  1447. }
  1448. /**
  1449. * get truncate query instance
  1450. * @param string|array $table
  1451. * @param boolean $newInstance
  1452. * @return mysqlClass_Truncate
  1453. */
  1454. public function truncate($table = NULL, $newInstance = false)
  1455. {
  1456. // prevent php debug notification
  1457. if( $table && $newInstance );
  1458. $args = array();
  1459. // check parameters for new instance
  1460. if( func_num_args() > 0 )
  1461. {
  1462. // extract last parameter
  1463. $args = func_get_args();
  1464. $last = array_splice($args, -1);
  1465. // if last parameter is a boolean
  1466. if( is_bool($last[0]) )
  1467. {
  1468. // if new instance has to be created
  1469. if( $last[0] )
  1470. {
  1471. $instance = new mysqlClass_Truncate($this);
  1472. if( !empty($args) )
  1473. call_user_func_array(array($instance, "table"), array($table));
  1474. return $instance;
  1475. }
  1476. }
  1477. // otherwise push parameter back in list
  1478. else
  1479. {
  1480. array_push($args, $last);
  1481. }
  1482. }
  1483. // create instance or reset
  1484. if( !$this->queryTruncate )
  1485. $this->queryTruncate = new mysqlClass_Truncate($this);
  1486. else
  1487. $this->queryTruncate->resetQuery($this->format);
  1488. // pass parameter
  1489. if( count($args) > 0 )
  1490. call_user_func_array(array($this->queryTruncate, "table"), array($table));
  1491. return $this->queryTruncate;
  1492. }
  1493. /**
  1494. * get truncate query instance
  1495. * @param string|array $table
  1496. * @param boolean $newInstance
  1497. * @return mysqlClass_Truncate
  1498. */
  1499. public function truncateTable($table = NULL, $newInstance = false)
  1500. {
  1501. // prevent php debug notification
  1502. if( $table && $newInstance );
  1503. return call_user_func_array(array($this, "truncate"), func_get_args());
  1504. }
  1505. }