search
HomeBackend DevelopmentPHP TutorialUltra-light PHP database toolkit

A very light PHP database toolkit, born two days ago (which is enough to prove that it is very light ).
Two classes, one Connection manages PDO connections (supports multiple databases), and one QuickQuery is used to quickly perform database operations (no need to toss back and forth between PDO and PDOStatement)
No need to download, you can watch it online.
  1. use PersistenceDbAccess;
  2. //Add connection information where the framework is initialized
  3. DbAccessConnection::add(
  4. 'default',
  5. 'sqlite',
  6. '/db/mydb.sqlite',
  7. null, null, false
  8. );
  9. // The following is using
  10. $conn = DbAccessConnection::instance('default');
  11. // Query
  12. $query = new DbAccessQuickQuery($conn);
  13. $query->prepare(' select :name as name')->execute(array(':name'=>'tonyseek'));
  14. // The object directly acts as an iterator to generate a data array
  15. foreach($query as $i) {
  16. var_dump($i);
  17. }
  18. // If you are paranoid, manually disconnect before outputting the response
  19. DbAccessConnection::disconnectAll();
Copy code
  1. namespace PersistenceDbAccess;
  2. use PDO, ArrayObject, DateTime;
  3. use LogicException, InvalidArgumentException;
  4. /**
  5. * Quick query channel
  6. *
  7. * @version 0.3
  8. * @author tonyseek
  9. * @link http://stu.szu.edu.cn
  10. * @license http://www.opensource.org/licenses/mit- license.html
  11. * @copyright StuCampus Development Team, Shenzhen University
  12. *
  13. */
  14. class QuickQuery implements IteratorAggregate
  15. {
  16. /**
  17. * Database connection
  18. *
  19. * @var PersistenceDbAccessConnection
  20. */
  21. private $connection = null;
  22. /**
  23. * PDO Statement
  24. *
  25. * @var PDOStatement
  26. */
  27. private $stmt = null;
  28. /**
  29. * Checked parameter set
  30. *
  31. * @var array
  32. */
  33. private $checkedParams = array();
  34. /* *
  35. * Construct query channel
  36. *
  37. * @param PersistenceDbAccessConnection $connection database connection
  38. */
  39. public function __construct(Connection $connection)
  40. {
  41. $this->connection = $connection;
  42. }
  43. /**
  44. * Precompiled SQL statement
  45. *
  46. * @param string $sqlCommand SQL statement
  47. * @return PersistenceDbAccessQuickQuery
  48. */
  49. public function prepare($sqlCommand)
  50. {
  51. // Obtain PDO from the connection and execute prepare on the SQL statement to generate PDO Statement
  52. $this->stmt = $this->connection->getPDO()->prepare($sqlCommand);
  53. // Modify the PDO Statement mode to associative array data
  54. $this->stmt->setFetchMode(PDO::FETCH_ASSOC);
  55. // Return method chain
  56. return $this;
  57. }
  58. /**
  59. * Execute data query
  60. *
  61. * @throws PDOException
  62. * @return PersistenceDbAccessQuickQuery
  63. */
  64. public function execute($params = array())
  65. {
  66. $stmt = $this->getStatement();
  67. // Parameter check
  68. $diff = array_diff($this->checkedParams, array_keys($params) );
  69. if (count($this->checkedParams) && count($diff)) {
  70. throw new InvalidArgumentException('Missing required parameter: '.implode(' | ', $diff));
  71. }
  72. // Correspond PHP data type to database data type
  73. foreach($params as $key => $value) {
  74. $type = null;
  75. switch(true) {
  76. case is_int($value):
  77. $type = PDO::PARAM_INT;
  78. break;
  79. case is_bool($value):
  80. $type = PDO::PARAM_BOOL;
  81. break;
  82. case ($value instanceof DateTime):
  83. $type = PDO::PARAM_STR;
  84. $value = $value->format(DateTime::W3C);
  85. break;
  86. case is_null($value):
  87. $type = PDO::PARAM_NULL;
  88. break;
  89. default:
  90. $type = PDO::PARAM_STR;
  91. }
  92. $stmt->bindValue($key, $value, $type);
  93. }
  94. $stmt->execute();
  95. $this->checkedParams = array(); // Clear parameter checks
  96. return $this;
  97. }
  98. /**
  99. * Get Statement object
  100. *
  101. * The returned object can be re-executed with bound parameters, or can be used as an iterator to traverse and obtain data.
  102. *
  103. * @return PDOStatement
  104. */
  105. public function getStatement()
  106. {
  107. if (!$this->stmt) {
  108. throw new LogicException('SQL statement should be QuickQuery.prepare first Preprocessing');
  109. }
  110. return $this->stmt;
  111. }
  112. /**
  113. * Alternative name for the getStatement method
  114. *
  115. * Implements the IteratorAggregate interface in the PHP standard library, and external parties can directly use this object as an iterator to traverse
  116. *. The only difference from getStatment is that this method does not throw LogicException. If
  117. * prepare and execute are not used beforehand, an empty iterator will be returned.
  118. *
  119. * @return Traversable
  120. */
  121. public function getIterator()
  122. {
  123. try {
  124. return $this->getStatement() ;
  125. } catch (LogicException $ex) {
  126. return new ArrayObject();
  127. }
  128. }
  129. /**
  130. * Set query parameter check
  131. *
  132. * Checked query parameters imported here, if not assigned , then a LogicException will be thrown during query.
  133. *
  134. * @param array $params
  135. * @return PersistenceDbAccessQuickQuery
  136. */
  137. public function setParamsCheck(array $params)
  138. {
  139. $this->checkedParams = $params;
  140. return $this;
  141. }
  142. /**
  143. * Convert the result set to an array
  144. *
  145. * @return array
  146. */
  147. public function toArray()
  148. {
  149. return iterator_to_array($this->getStatement());
  150. }
  151. /**
  152. * Get the ID of the last inserted result (or sequence)
  153. *
  154. * @param string $name
  155. * @return int
  156. */
  157. public function getLastInsertId($name=null)
  158. {
  159. return $this->connection->getPDO()->lastInsertId($name);
  160. }
  161. }
复制代码
  1. namespace PersistenceDbAccess;
  2. use InvalidArgumentException, BadMethodCallException;
  3. use PDO, PDOException;
  4. /**
  5. * Connection factory, provides global PDO objects, and manages transactions.
  6. *
  7. * @version 0.3
  8. * @author tonyseek
  9. * @link http://stu.szu.edu.cn
  10. * @license http://www.opensource.org/licenses/mit-license.html
  11. * @copyright StuCampus Development Team, Shenzhen University
  12. *
  13. */
  14. final class Connection
  15. {
  16. /**
  17. * Connector instance collection
  18. *
  19. * @var array
  20. */
  21. static private $instances = array();
  22. /**
  23. * Database driver name
  24. *
  25. * @var string
  26. */
  27. private $driver = '';
  28. /**
  29. * Database connection string (Database Source Name)
  30. *
  31. * @var string
  32. */
  33. private $dsn = '';
  34. /**
  35. * PDO instance
  36. *
  37. * @var PDO
  38. */
  39. private $pdo = null;
  40. /**
  41. * Username
  42. *
  43. * @var string
  44. * /
  45. private $username = '';
  46. /**
  47. * Password
  48. *
  49. * @var string
  50. */
  51. private $password = '';
  52. /**
  53. * Whether to enable persistent connections
  54. *
  55. * @var bool
  56. */
  57. private $isPersisten = false;
  58. /**
  59. * Whether to enable simulation pre-compilation
  60. *
  61. * @var bool
  62. */
  63. private $isEmulate = false;
  64. /**
  65. * Whether in transaction
  66. *
  67. * @var bool
  68. */
  69. private $isInTransation = false;
  70. /**
  71. * Private constructor, preventing external instantiation using the new operator
  72. */
  73. private function __construct(){}
  74. /* *
  75. * Production Connector instance (multiple instances)
  76. *
  77. * @param string $name
  78. * @return StuCampusDataModelConnector
  79. */
  80. static public function getInstance($name = 'default')
  81. {
  82. if (!isset(self::$instances[$name])) {
  83. // Throws if the accessed instance does not exist An error occurred
  84. throw new InvalidArgumentException("[{$name}] does not exist");
  85. }
  86. return self::$instances[$name];
  87. }
  88. /**
  89. * Disconnect all database instances
  90. */
  91. static public function disconnectAll()
  92. {
  93. foreach (self::$instances as $instance) {
  94. $instance->disconnect();
  95. }
  96. }
  97. /**
  98. * Add database
  99. *
  100. * Add Connector to the instance group
  101. *
  102. * @param string $name identification name
  103. * @param string $driver driver name
  104. * @param string $dsn connection string
  105. * @param string $usr Database username
  106. * @param string $pwd Database password
  107. * @param bool $emulate Simulation precompiled query
  108. * @param bool $persisten Whether to persist the connection
  109. */
  110. static public function registry($ name, $driver, $dsn, $usr, $pwd, $emulate = false, $persisten = false)
  111. {
  112. if (isset(self::$instances[$name])) {
  113. // If the added instance If the name already exists, an exception will be thrown
  114. throw new BadMethodCallException("[{$name}] has been registered");
  115. }
  116. // Instantiate itself and push it into the array
  117. self::$instances[$name] = new self();
  118. self::$instances[$name]->dsn = $driver . ':' . $dsn;
  119. self::$instances[$name]->username = $usr;
  120. self::$instances[$name]->password = $pwd;
  121. self::$instances[$name]->driver = $driver;
  122. self::$instances[$name]->isPersisten = (bool)$persisten;
  123. self::$instances[$name]->isEmulate = (bool)$emulate;
  124. }
  125. /**
  126. * Get PHP Database Object
  127. *
  128. * @return PDO
  129. */
  130. public function getPDO()
  131. {
  132. if ( !$this->pdo) {
  133. // Check whether PDO has been instantiated, otherwise instantiate PDO first
  134. $this->pdo = new PDO($this->dsn, $this->username, $ this->password);
  135. // The error mode is to throw a PDOException exception
  136. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  137. // Enable query caching
  138. $this- >pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->isEmulate);
  139. // Enable persistent connections
  140. $this->pdo->setAttribute(PDO::ATTR_PERSISTENT, $this->isPersisten );
  141. }
  142. return $this->pdo;
  143. }
  144. /**
  145. * Get the database driver name
  146. *
  147. * @return string
  148. */
  149. public function getDriverName()
  150. {
  151. return $this->driver;
  152. }
  153. /* *
  154. * Start transaction
  155. */
  156. public function translationBegin()
  157. {
  158. $this->isInTransation = $this->getPDO()->beginTransaction();
  159. }
  160. /**
  161. * Submit transaction
  162. */
  163. public function transationCommit()
  164. {
  165. if ($this->isInTransation) {
  166. $this->getPDO()->commit();
  167. } else {
  168. trigger_error('transationBegin should be called before transationCommit') ;
  169. }
  170. }
  171. /**
  172. * Rollback transaction
  173. * @return bool
  174. */
  175. public function translationRollback()
  176. {
  177. if ($this->isInTransation) {
  178. $this->getPDO()->rollBack();
  179. } else {
  180. trigger_error('transationBegin should be called before transationRollback');
  181. }
  182. }
  183. /**
  184. * Whether the connection is in the transaction
  185. *
  186. * @return bool
  187. */
  188. public function isInTransation()
  189. {
  190. return $this->isInTransation;
  191. }
  192. /**
  193. * Execute the callback function in the transaction
  194. *
  195. * @param function $callback anonymous function or closure function
  196. * @param bool $autoRollback Whether to automatically roll back when an exception occurs
  197. * @throws PDOException
  198. * @return bool
  199. */
  200. public function transationExecute($callback, $autoRollback = true)
  201. {
  202. try {
  203. // Start transaction
  204. $this->transationBegin();
  205. // Call callback function
  206. if (is_callable($callback)) {
  207. $callback();
  208. } else {
  209. throw new InvalidArgumentException('$callback should be a callback function');
  210. }
  211. // Commit the transaction
  212. return $this->transationCommit();
  213. } catch(PDOException $pex) {
  214. // If automatic rollback is enabled, Then when catching the PDO exception, roll it back first and then throw it
  215. if ($autoRollback) {
  216. $this->transationRollback();
  217. }
  218. throw $pex;
  219. }
  220. }
  221. /**
  222. * Safely disconnect from database
  223. */
  224. public function disconnect()
  225. {
  226. if ($this->pdo) {
  227. // Check whether PDO has been instantiated, if so, set it to null
  228. $this->pdo = null;
  229. }
  230. }
  231. /**
  232. * Block cloning
  233. */
  234. public function __clone()
  235. {
  236. trigger_error('Blocked __clone method, Connector is a singleton class');
  237. }
  238. }
Copy code


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment