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

  • Home
  • SEARCH
  • 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 6877873
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T04:39:12+00:00 2026-05-27T04:39:12+00:00

In the past, I’ve always created a database class and in that class assigned

  • 0

In the past, I’ve always created a database class and in that class assigned a $connection attribute the connection via mysql_connect in a __construct method. In the same file, I would instantiate the class so that it was ready to go. Then whenever I needed that connection I would simply require that database file and add a global $connection in the method that need the $connection. What is the best way to achieve something similar or better using php’s PDO?

  • 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-27T04:39:13+00:00Added an answer on May 27, 2026 at 4:39 am

    I believe that there’s no “Best” way to achieve what you ask but here is what I use. The function execute was designed according to my needs, you may change it however you want.

    ** EDIT **

    By the way, I am using a singleton method in this class since I call the class several times from different files. Therefore, you may change that as well.

    class DB
    {
        /* Connection settings */
        private static $host = 'localhost';
        private static $user = 'root';
        private static $pass = 'your_pass';
        private static $base = 'your_db';
    
        private static $ins;   // pdo instance
        private static $class; // class object for singleton
    
        public static $counter; // counts how many times execute is called
    
        public function __construct()
        {
    
        }
    
        public static function connect($errMode = PDO::ERRMODE_SILENT)
        {
            if (!isset(self::$ins))
            {
                try 
                {
                    self::$ins = new PDO("mysql:host=" . self::$host . ";" ."dbname=" . self::$base . ";", self::$user, self::$pass);
                    self::$ins->setAttribute(PDO::ATTR_ERRMODE, $errMode);
                    // PDO::ERRMODE_EXCEPTION
                }
                catch (Excpetion $ex) 
                {
                    self::raiseError($ex);
                }
                $className = __CLASS__;
                self::$class = new $className;
            }
            return self::$class;
        }
    
        /**
         * Function to execute a given query
         * @param string $query : query string
         * @param string | array $param : parameter (either array of parameters or string)
         * @param bool $useBind : if true bindParam method will be used, else execute method will be called
         * @return PDOStatement
         */
        public function execute($query, $param, $useBind=true)
        {   
            self::$counter++;
            $stmt = self::$ins->prepare($query);
    
            if (!$useBind)
                $stmt->execute($param);
            else
            {
                if (is_array($param))
                {
                    $size = sizeof($param);
                    // if items within param param are array (e.g. array(array(value, name, type, length),
                    //                                                   array(value, name, type, length))
                    if ($size >= 1 && is_array($param[0]))
                    {
                        $i = 1; // ? placeholder counter
                        foreach ($param as $arr)
                        {
                            $size = sizeof($arr);
                            if ($size == 1) // e.g. array('red')
                                $stmt->bindParam($i, $arr[0]);
                            else if ($size == 2) // e.g. array(':color', 'red')
                                $stmt->bindParam($arr[0], $arr[1]);
                            else if ($size == 3) // e.g. array(':color', 'red', PDO::PARAM_STR)
                                $stmt->bindParam($arr[0], $arr[1], $arr[2]);
                            else // e.g. array(':color', 'red', PDO::PARAM_STR, 12)
                                $stmt->bindParam($arr[0], $arr[1], $arr[2], $arr[3]);
                            $i++;
                        }
                    }
                    else if ($size == 1) // e.g. array(15)
                        $stmt->bindParam(1, $param[0]);
                    else if ($size == 2) // e.g. array(':color', 'red')
                        $stmt->bindParam($param[0], $param[1]);
                    else if ($size == 3) // e.g. array(':color', 'red', PDO::PARAM_STR)
                        $stmt->bindParam($param[0], $param[1], $param[2]);
                    else if ($size == 4) // e.g. array(':color', 'red', PDO::PARAM_STR, 12)
                        $stmt->bindParam($param[0], $param[1], $param[2], $param[3]);
                }
                else // e.g. $db::execute($query, 15)
                    $stmt->bindParam(1, $param);
                $stmt->execute();
            }
    
            return $stmt;
        }
    
        public function query($query)
        {
            self::$counter++;
            $result = self::$ins->query($query);
            return $result;
        }
    
        public function close()
        {
            self::$ins = null;
        }
    
        public function lastId()
        {
            $id = self::$ins->lastInsertId();
            return $id;
        }
    
        public function trans()
        {
            self::$ins->beginTransaction();
        }   
    
        public function commit()
        {
            self::$ins->commit();
        }
    
        public function rollBack()
        {
            self::$ins->rollBack();
        }
    
        private function raiseError($er)
        {
            throw new Exception($er);
        }
    
        public function counter()
        {
            return self::$counter;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In past I use dynamic sql and datatable to get data from database. Such
In the past I've never been a fan of using triggers on database tables.
From past few days I'm trying to develop a regex that fetch all the
For the past few years I've continuously struggled with unit testing database code and
for the past months, googleBot has been hitting a file that does not exist
In the past while working with MVVM I've created every View as a DataTemplate
In the past, I used swiftsuspenders that is an actionscript 3 IoC controller. Basically
For past projects(the last few have been web using asp.net mvc) we created a
In one of my past questions, a answerer suggests me that it is better
In the past I've used profman2 to create MAPI profiles for servers that need

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.