【问题标题】:How can I use one connection for 2 or more functions?如何将一个连接用于 2 个或更多功能?
【发布时间】:2013-01-10 14:21:51
【问题描述】:

我使用 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"; 
}

【问题讨论】:

标签: php mysql function pdo connection


【解决方案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"; 

不过我认为这是不好的编码风格。

【讨论】:

  • 不,tnks 不行!我认为应该使用 public function(),你知道它以及如何使用它吗?
  • 我不能在这里测试它,但我很确定它确实有效。将上面的两行放在像connection() 这样的函数中。然后像在第二个代码块中那样调用你的函数。
  • 我扩展了我的答案以更详细地解释它。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    相关资源
    最近更新 更多