0

I have the following code that works, but I am wondering what would be a better approach to this technique? I would like to start reusing connections instead of creating new instances for each query. Any practical advise and solution to my code?

<?php
class dbc {
    function openDb() {

        $dbserver = '';
        $dbusername = '';
        $dbpassword = '';
        $dbname = '';

        try {
            $db = new PDO('mysql:host=' . $dbserver . ';port=3306;dbname=' . $dbname . ';charset=utf8', '' . $dbusername . '', '' . $dbpassword . '', array(PDO::MYSQL_ATTR_INIT_COMMAND =>"SET SESSION time_zone = 'America/Chicago'"));
            $timezone = "America/Chicago";
            $db->exec("SET time_zone = '{$timezone}'");  

        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die("error, please try again");
        }
        return $db;
    }
}

<?php    
require 'dbc.php';

function getDailyProfitability() {
    $db = new dbc();
    $query = "SELECT 1 FROM DUAL";
    $stmt = $db->openDb()->prepare($query);
    $stmt->execute();
    return $stmt->fetchAll();
}    
?>

1 Answer 1

1

Not sure if this is exactly what you're looking for but I found this article that talks about using a static variable to store your database connection.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.