Home >Database >Mysql Tutorial >How to Integrate PDO with PHP Classes Using Prepared Statements?
Class-Based PDO Integration
Question:
How can PDO be incorporated within PHP classes to perform database operations using prepared statements?
Solution:
Utilizing Object-Oriented Singleton Pattern:
Consider employing a singleton pattern to manage database connections. This pattern ensures that a database connection is established only once and accessible globally by your applications.
To implement this:
Example:
<code class="php">class Core { public $dbh; private static $instance; private function __construct() { // Initialize connection using PDO parameters } public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } }</code>
Using Core Class in Other Objects:
<code class="php">// Retrieve Core instance $core = Core::getInstance(); // Prepare and execute queries using the database connection $stmt = $core->dbh->prepare("SELECT * FROM table"); $stmt->execute();</code>
Additional Notes:
The above is the detailed content of How to Integrate PDO with PHP Classes Using Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!