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 8192301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T04:08:43+00:00 2026-06-07T04:08:43+00:00

From time to time I see questions regarding connecting to database. Most answers is

  • 0

From time to time I see questions regarding connecting to database.
Most answers is not the way I do it, or I might just not get the answers correctly. Anyway; I’ve never thought about it because the way I do it works for me.

But here’s a crazy thought; Maybe I’m doing this all wrong, and if that’s the case; I would really like to know how to properly connect to a MySQL database using PHP and PDO and make it easy accessible.

Here’s how I’m doing it:

First off, here’s my file structure (stripped down):

public_html/

* index.php  

* initialize/  
  -- load.initialize.php  
  -- configure.php  
  -- sessions.php   

index.php
At the very top, I have require('initialize/load.initialize.php');.

load.initialize.php

#   site configurations
    require('configure.php');
#   connect to database
    require('root/somewhere/connect.php');  //  this file is placed outside of public_html for better security.
#   include classes
    foreach (glob('assets/classes/*.class.php') as $class_filename){
        include($class_filename);
    }
#   include functions
    foreach (glob('assets/functions/*.func.php') as $func_filename){
        include($func_filename);
    }
#   handle sessions
    require('sessions.php');

I know there’s a better, or more correct, way to include classes, but can’t remember what it was. Haven’t gotten the time to look into it yet, but I think it was something with autoload. something like that…

configure.php
Here I basically just override some php.ini-properties and do some other global configuration for the site

connect.php
I’ve put the connection onto a class so other classes can extends this one…

class connect_pdo
{
    protected $dbh;

    public function __construct()
    {
        try {
            $db_host = '  ';  //  hostname
            $db_name = '  ';  //  databasename
            $db_user = '  ';  //  username
            $user_pw = '  ';  //  password

            $con = new PDO('mysql:host='.$db_host.'; dbname='.$db_name, $db_user, $user_pw);  
            $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $con->exec("SET CHARACTER SET utf8");  //  return all sql requests as UTF-8  
        }
        catch (PDOException $err) {  
            echo "harmless error message if the connection fails";
            $err->getMessage() . "<br/>";
            file_put_contents('PDOErrors.txt',$err, FILE_APPEND);  // write some details to an error-log outside public_html  
            die();  //  terminate connection
        }
    }

    public function dbh()
    {
        return $this->dbh;
    }
}
#   put database handler into a var for easier access
    $con = new connect_pdo();
    $con = $con->dbh();
//

Here I do believe there’s room for massive improvement since I recently started learning OOP, and using PDO instead of mysql.
So I’ve just followed a couple of beginners tutorials and tried out different stuff…

sessions.php
Beside handling regular sessions, I also initialize some classes into a session like this:

if (!isset($_SESSION['sqlQuery'])){
    session_start();
    $_SESSION['sqlQuery'] = new sqlQuery();
}

This way this class is available all over the place. This might not be good practice(?)…
Anyway, this is what this approach allows me to do from everywhere:

echo $_SESSION['sqlQuery']->getAreaName('county',9);  // outputs: Aust-Agder (the county name with that id in the database)

Inside my sqlQuery–class, which extends my connect_pdo–class, I have a public function called getAreaName which handles the request to my database.
Pretty neat I think.

Works like a charm
So that’s basically how I’m doing it.
Also, whenever I need to fetch something from my DB from not within a class, I just do something similar to this:

$id = 123;

$sql = 'SELECT whatever FROM MyTable WHERE id = :id';
$qry = $con->prepare($sql);
$qry -> bindParam(':id', $id, PDO::PARAM_INT);
$qry -> execute();
$get = $qry->fetch(PDO::FETCH_ASSOC);

Since I put the connection into a variable inside connect_pdo.php, I just have referring to it and I’m good to go. It works. I get my expected results…

But regardless of that; I would really appreciate if you guys could tell me if I’m way off here. What I should do instead, areas I could or should change for improvement etc…

I’m eager to learn…

  • 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-06-07T04:08:44+00:00Added an answer on June 7, 2026 at 4:08 am

    The goal

    As I see it, your aim in this case is twofold:

    • create and maintain a single/reusable connection per database
    • make sure that the connection has been set up properly

    Solution

    I would recommend to use both anonymous function and factory pattern for dealing with PDO connection. The use of it would looks like this :

    $provider = function()
    {
        $instance = new PDO('mysql:......;charset=utf8', 'username', 'password');
        $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        return $instance;
    };
    
    $factory = new StructureFactory( $provider );
    

    Then in a different file or lower in the same file:

    $something = $factory->create('Something');
    $foobar = $factory->create('Foobar');
    

    The factory itself should look something like this:

    class StructureFactory
    {
        protected $provider = null;
        protected $connection = null;
    
        public function __construct( callable $provider )
        {
            $this->provider = $provider;
        }
    
        public function create( $name)
        {
            if ( $this->connection === null )
            {
                $this->connection = call_user_func( $this->provider );
            }
            return new $name( $this->connection );
        }
    
    }
    

    This way would let you have a centralized structure, which makes sure that connection is created only when required. It also would make the process of unit-testing and maintenance much easier.

    The provider in this case would be found somewhere at the bootstrap stage. This approach would also give a clear location where to define the configuration, that you use for connecting to the DB.

    Keep in mind that this is an extremely simplified example. You also might benefit from watching two following videos:

    • Global State and Singletons
    • Don’t Look For Things!

    Also, I would strongly recommend reading a proper tutorial about use of PDO (there are a log of bad tutorial online).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

From time to time I see something like this: class Clazz { private int
I want to see if a time I read from a db overlaps with
there are similar questions but not clear answer around using sqlite db from multiple
From time to time, I find myself using the same group of statements and
From time to time I run into the issue that Grails integration tests the
From time time to time, I'd like to be able to measure the elapsed
From time to time I need to run a full build of the entire
From time to time, Oracle is changing the password for my account. My project
Hi from time to time , i want to shutdown my site for maintenance
I change schema.yml from time to time and execute: symfony propel:build-all-load but the lib/_model

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.