如何为一个或多个功能使用一个连接?

时间:2013-01-10 14:21:52

标签: php mysql function pdo connection

我使用PHP的PDO连接到MySQL。我有这个连接代码:

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

我在另一个档案中有一个功能:

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"; 
}

我可以使用include connect.php文件,但事实并非如此。

我想使用一个函数如connection()连接到所有其他函数的mysql,例如:

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"; 
}

2 个答案:

答案 0 :(得分:1)

这是功能。把它放在你喜欢的任何文件中。

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" );
}

这是您的主要代码。如果您决定将文件放在另一个文件中,请将文件包含在上面的代码中。

connection();

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

我认为它的编码风格很糟糕。

答案 1 :(得分:0)

我为我的问题找到了最佳解决方案(如何将MYSQL连接用于一个或多个功能):

$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.