0

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"; 
}
elitalon
  • 9,191
  • 10
  • 50
  • 86
Maher
  • 2,517
  • 1
  • 19
  • 32
  • Do not use `->exec("SET NAMES utf8")`; instead add [`;charset=utf8` to the end of your DSN](http://php.net/manual/en/ref.pdo-mysql.connection.php) or the `MYSQL_ATTR_INIT_COMMAND` workaround described there if your PHP version is too old. This [PDO connection convenience function](http://stackoverflow.com/a/10455228/1002469) will take care of all the vulgarities of connecting properly in different PHP versions. – Francis Avila Jan 10 '13 at 14:58

2 Answers2

1

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.

Thomas Tschernich
  • 1,264
  • 15
  • 29
0

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.
Maher
  • 2,517
  • 1
  • 19
  • 32