PHP-PDO 'config' file equivalent

This may be a question that has been answered before - if so, just leave a comment below and I will delete it.

I studied classes in PHP and at the same time made the transition to PDO.

One concept that I cannot find is how to learn the equivalent of this to classes:

config.php

<?php $host = 'localhost'; $user = 'user'; $pass = 'pass'; $con = mysql_connect($host, $user, $pass) or die("MySQL Error"); mysql_select_db("account_db", $con); ?> 

another.php

 <?php require_once('config.php'); $selectStatement = "SELET foo FROM bar"; $selectQuery = mysql_query($selectStatement, $con); ?> 

I did not quite understand how to create a configuration file / class for a PDO connection, and then use it in another class, i.e. users, as shown below:

 <?php class Users { private $_userId; function setUserId($username) { // Use a predefined database handle to connect to a database to get the users ID - I assume using a preconfigured $dbh handle via an include or extend? $sth = $dbh->prepare("SELECT id FROM users WHERE username = :username"); $sth->bindParam(':username', $username); ... } } ?> 

Thanks everyone :)

+4
source share
1 answer

In my projects, I prefer to use a class with a static member that contains a PDO object.

 <?php class DB { private static $instance = null; public static function get() { if(self::$instance == null) { try { self::$instance = new PDO('mysql:host=localhost;dbname=name', 'user', 'abc123'); } catch(PDOException $e) { // Handle this properly throw $e; } } return self::$instance; } } 

I can access it like this:

 <?php require 'DB.php'; class Users { private $_userId; function setUserId($username) { // Using DB::get() to get the PDO object $sth = DB::get()->prepare("SELECT id FROM users WHERE username = :username"); $sth->bindParam(':username', $username); ... } } 
+6
source

Source: https://habr.com/ru/post/1343808/


All Articles