Using existing MySQL database connection?

Using existing MySQL database connection?

alcandaalcanda Posts: 4Questions: 2Answers: 0

Hello,

I am trying to get the Editor using an already existing database connection, with no success. I have the following code:

// Here I already have a PDO database connection => $dbh

include( "Datatables/DataTables.php" );

Editor::inst( $db, 'table' )...  

Everything is working fine so far, but I would like to use $dbh instead of providing the MySQL credentials in config.php, simply because I do not want to maintain the database connection credentials twice, as my code is running in different environments (development, qa, production) with different sql credentials. My $dbh always has the appropriate environment credentials.

Is there a way to accomplish that? I am sorry if this has already been answered, but I could not find anything and was too dumb to find a solution by myself.

Thanks!

Ben

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Hi Ben,

    You can't use just a plain PDO resource as the first parameter for Editor as it expects a Database class from the library. I've just made a change in the libraries to let you use an existing PDO resource (thanks for the suggestion, not sure why I didn't think of it before!). It will be in the 1.4.1 release which will be in the next couple of days, but if you want to make the change immediately, change the constructor for the Database class to be:

        function __construct( $opts )
        {
            $this->query_driver = "DataTables\\Database\\Driver".$opts['type'].'Query';
            $this->_db = isset( $opts['pdo'] ) ?
                $opts['pdo'] :
                call_user_func($this->query_driver.'::connect', $opts );
        }
    

    Then update your $sql_details array to be something like:

    $sql_details = [
      'type' => 'Mysql',
      'pdo' => $dbh
    ];
    

    Regards,
    Allan

  • alcandaalcanda Posts: 4Questions: 2Answers: 0

    Hi Allan,

    thank you so much, works like a charm!

    Regards,
    Ben

This discussion has been closed.