Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7638707
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T08:14:17+00:00 2026-05-31T08:14:17+00:00

I’m trying to understand how to use PDO with a connection class. class db

  • 0

I’m trying to understand how to use PDO with a “connection” class.

class db { 

    private static $dbh; 

    private function __construct(){}
    private function __clone(){} 

    public static function connect() { 
        if(!self::$dbh){ 
            self::$dbh = new PDO("mysql:host=localhost;dbname=database", "user", "password");
            self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
        } 
        return self::$dbh; 
    } 

    final public static function __callStatic( $chrMethod, $arrArguments ) {   
        $dbh = self::connect(); 
        return call_user_func_array(array($dbh, $chrMethod), $arrArguments);  
    }
} 

I’ve taken the above from http://php.net/manual/en/book.pdo.php, and modified the variables slightly but I’m wondering how I then connect to the PDO connection object within this db class?

$dbh = new db; //intiate connection???

$stmt = $dbh->prepare("SELECT * FROM questions WHERE id = :id"); // or should I do db::prepare.. ???
$stmt->bindParam(':id', $_GET['testid'], PDO::PARAM_INT);

if ($stmt->execute()) {
    while ($row = $stmt->fetch()){
        print_r($row);
    }
}

Any ideas please? thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T08:14:18+00:00Added an answer on May 31, 2026 at 8:14 am

    This is more or less how I do it. I’m not sure if this is the best way of doing it, but it works for me.

    My factory class is the CORE of my code. From here I generate all classes I work with. My factory class is saved in a separate file factory.class.php.

    By having a factory class, I only need to include class files only once. If I did not have this, I would have to include my class files for each file having to use it. If I need to update a class file name later, I only need to make the update in factory class file.

    Another reason for creating a factory object, was to reduce the number of DB connections.

    I save each class as a separate file

    Factory class

    include_once('person.class.php');
    include_once('tracking.class.php');
    include_once('costAnalyzis.class.php');
    include_once('activity.class.php');
    
    class Factory {
      function new_person_obj($id = NULL) { return new Person(Conn::get_conn(), $id); }  
      function new_tracking_obj($id = NULL) { return new Tracking(Conn::get_conn(), $id); }
      function new_costAnalyzis_obj() { return new CostAnalyzis(Conn::get_conn()); }
      function new_activity_obj() { return new Activity(Conn::get_conn()); }
    }    
    

    Connection class

    // I have this class in the same file as Factory class
    // This creates DB connection and returns any error messages
    class Conn {
      private static $conn = NULL;
    
      private function __construct() {}
    
      private static function init() {
          $conf = self::config();
          try { 
            self::$conn = new PDO($conf['dsn'], $conf['user'], $conf['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
          } 
          catch (PDOException $e) {
            // We remove the username if we get [1045] Access denied
            if (preg_match("/\b1045\b/i", $e->getMessage())) 
              echo "SQLSTATE[28000] [1045] Access denied for user 'name removed' @ 'localhost' (using password: YES)";
            else
              echo $e->getMessage();  
          }
      }
    
      public static function get_conn() {
        if (!self::$conn) { self::init(); }
        return self::$conn;
      }
    
      // I used to get login info from config file. Now I use WordPress constants
      private static function config() {
        $conf = array();
    
        $conf['user']    = DB_USER; //$config['db_user'];
        $conf['pass']    = DB_PASSWORD; //$config['db_password'];
        $conf['dsn']     = 'mysql:dbname='.DB_NAME.';host='.DB_HOST;
    
        return $conf;
      }  
    }
    

    Different class objects

    These are your classes. This is where you work with your data In my own code I’m using tri-tier architecture, separating presentation, from business layer and data object layer.

    class Person extends PersonDAO {
    
      function getPersonData($id) {
        $result = parent::getPersonData($id);
    
        // Here you can work with your data. If you do not need to handle data, just return result
        return $result;
      }
    }
    
    
    // I only have SQL queries in this class and I only return RAW results.
    class PersonDAO {
    
      // This variable is also available from you mother class Person 
      private $db;
    
        // Constructor. It is automatically fired when calling the function.
        // It must have the same name as the class - unless you define 
        // the constructor in your mother class.
        // The &$db variable is the connection passed from the Factory class.
        function PersonDAO (&$db) {
          $this->db = &$db;
        }
    
    
      public function get_data($id) {
         $sql ="SELECT a, b, c
              FROM my_table
              WHERE id = :id";
    
         $stmt = $this->db->prepare($sql);
         $stmt->execute(array(':id'=> $id));
         $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
         return $result;
      }
    
      public function get_some_other_data() {
        $sql ="SELECT a, b, c
              FROM my_table_b";
    
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        return $result;      
      }
    }
    

    Do the same for your other classes.

    Putting it all together

    Notice that we only include one file, the factory files. All other class files are included in Factory class file.

    // Include factory file
    include_once('factory.class.php');
    
    //Create your factory object
    $person = Factory::new_person_obj();
    
    //Get person data
    $data = $person->getPersonData('12');
    
    // output data
    print_r($data);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
public static bool CheckLogin(string Username, string Password, bool AutoLogin) { bool LoginSuccessful; // Trim
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to render a haml file in a javascript response like so:
I am doing a simple coin flipping experiment for class that involves flipping a
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.