Home > Article > Backend Development > How to manage database connections and queries in PHP microservices
How to manage database connections and queries in PHP microservices
When developing PHP microservices, database connections and queries are a very important part. Properly managing database connections and queries can improve code maintainability and performance. This article will introduce how to correctly manage database connections and queries in PHP microservices, and provide specific code examples.
The following is an example of using PDO to connect to a MySQL database:
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8'; $username = 'root'; $password = ''; try { $db = new PDO($dsn, $username, $password); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo '连接数据库失败:' . $e->getMessage(); }
The following is a simple database connection singleton example:
class Database { private static $instance; private $db; private function __construct() { $dsn = 'mysql:host=localhost;dbname=test;charset=utf8'; $username = 'root'; $password = ''; try { $this->db = new PDO($dsn, $username, $password); $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo '连接数据库失败:' . $e->getMessage(); } } public static function getInstance() { if (!self::$instance) { self::$instance = new self(); } return self::$instance; } public function getDB() { return $this->db; } } // 使用方式 $db = Database::getInstance()->getDB();
The following is an example of using PDO prepared statements to execute queries:
$username = 'admin'; $password = '123456'; // 预处理语句 $stmt = $db->prepare('SELECT * FROM users WHERE username = :username AND password = :password'); $stmt->bindParam(':username', $username); $stmt->bindParam(':password', $password); // 执行查询 $stmt->execute(); // 获取查询结果 $result = $stmt->fetchAll(PDO::FETCH_ASSOC); // 处理查询结果 foreach ($result as $row) { // ... }
In summary, correctly managing database connections and queries is very important for the development of PHP microservices. Using PDO extensions to connect to the database and using the singleton pattern to manage database connections can improve the maintainability and performance of the code. At the same time, using prepared statements to execute queries can effectively prevent SQL injection attacks and improve query performance. I hope this article can help you better manage database connections and queries in PHP microservices.
Please note that the above sample code is for demonstration purposes only. Please adjust and optimize it according to the actual situation during actual development.
The above is the detailed content of How to manage database connections and queries in PHP microservices. For more information, please follow other related articles on the PHP Chinese website!