Maher
Maher

Reputation: 2547

How can I use one connection for 2 or more functions?

I use PHP's PDO to connect to MySQL. I have this code for connection:

$dbh = new PDO ( $db_host.$db_database, $db_user, $db_pass );
$dbh->exec ( "set names utf8" );

I have a function in another file:

function Image()
{
    include 'config/connect.php';
    #connected         

    $sql = 'Select * from settings where name="X" ';
    $stmt = $dbh->prepare($sql);
    $stmt->execute();
    $row = $stmt->fetchObject();
    $Template = $row->web_site_template;
    echo "Template"; 
}

I can use include connect.php file for that, but it's not true.

I want use one function like connection() for connect to the mysql on all other functions, like:

function Image()
{
    connection();

    $sql = 'Select * from settings where name="X" ';
    $stmt = $dbh->prepare($sql);
    $stmt->execute();
    $row = $stmt->fetchObject();
    $Template = $row->web_site_template;
    echo "Template"; 
}

Upvotes: 0

Views: 136

Answers (2)

Maher
Maher

Reputation: 2547

I find a best solution for my question (How you can use a MYSQL connection for 1 or more functions):

$db_database ="YourTableName";
$db_user     ="YourUsername";
$db_pass     ="YourPassword";
$db_host     ="YourHostName";

$dbh = new PDO ( "mysql:host=$db_host;dbname=$db_database", $db_user, $db_pass );
$dbh->exec ( "set names utf8" );

$database = $dbh; // Here you can use $dbh too, but I use $database to understand the difference here .

#start function
function Template(){
    global $database; //use $database as global

    $sql = 'Select * from YourTableName where column="Record"';
    $stmt = $database->prepare($sql); //use $database Instead $dbh 
    $stmt->execute();
    $row = $stmt->fetchObject();
    $Template = $row->web_site_template;
    echo $Template; 
   }

Template(); // Here is your result.

Upvotes: 0

Thomas Tschernich
Thomas Tschernich

Reputation: 1282

This is the function. Put it in any file you like to.

function connection() { 
$db_host = "..."; $db_database = "..."; $db_user = "..."; $db_pass = "...";
$GLOBALS["dbh"] = new PDO ( $db_host.$db_database, $db_user, $db_pass );
$GLOBALS["dbh"]->exec ( "set names utf8" );
}

This is your main code. Include the file with the code above if you decided to put it in another file.

connection();

$sql = 'Select * from settings where name="X" ';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$row = $stmt->fetchObject();
$Template = $row->web_site_template;
echo "Template"; 

I would consider it bad coding style though.

Upvotes: 1

Related Questions