I have used PDO DB connection in my custom module. I wanted to know how can I access the Database variables from (settings file) in my custom module. Or is there any way to make PDO DB connection globally so that it can be used every where it needed in custom module.

My code is below:

function my_module_init() {





    $servername ="host";
    $username = "test1";
    $password = "test2";
    $dbname = "test3";        

    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);        
    $query = $conn->exec("TRUNCATE TABLE table_name");

    $sql = "INSERT INTO table_name (test_id)
    VALUES ('$test_id')";
    $conn = null;        


closed as off-topic by Kevin, Clive Feb 13 '17 at 14:26

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions on programming, PHP, SQL, etc. that do not relate directly to Drupal are off-topic here, but can be asked on Stack Overflow." – Clive
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    I you're just writing custom PHP code you should do it whichever way you're comfortable doing it. If you start using the Drupal API at any point please ask a specific question about that – Clive Feb 13 '17 at 14:25

You don't need to access the connection variables directly. Drupal 7 comes with a full database API that handles the connection for you, and can be used from anywhere in your module. Some common functions in the API are db_query(), db_select(), db_insert(), db_update, db_delete() and db_merge()

You can read all about the Database API here: https://www.drupal.org/docs/7/api/database-api/database-api-overview

  • db_merge is my favorite – No Sssweat Feb 14 '17 at 0:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.