PDO对象无法访问函数内部

时间:2016-03-17 14:37:36

标签: php mysql pdo

在我的项目中,我有一个名为connection.inc.php的文件,它使用PDO管理数据库连接。

包含/ connection.inc.php

 <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
?>

我将此文件包含在其他各个页面中,它对我来说非常有用。但是当我试图访问函数内的$conn对象时,它无效。如何解决这个问题。

4 个答案:

答案 0 :(得分:2)

你可以在你的功能上做global $conn,但不要。我建议把它包装成单身。

<?php
class Connection {

    private static $conn = null;

    private $connection = null;

    private function __construct() {
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "college";

        try {
            $this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
            // set the PDO error mode to exception
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage(); // Should look into a different error handling mechanism 
        }
    }

    public static function getConnection() {
        if (self::$conn === null) {
            self::$conn = new self();
        }
        return self::$conn->connection;
    }

}

您可以通过Connection::getConnection()

访问它

如果当前请求不需要使用它,这也具有不初始化连接的优点。

答案 1 :(得分:0)

您需要将文件更新为

<?php
   $servername = "localhost";
   $username = "root";
   $password = "";
   $dbname = "college";
   //// define global variable
   global $connection

 try {
   $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
   /// assign the global variable value
   $connection = $conn ;
 // set the PDO error mode to exception
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 }

 catch(PDOException $e)
 {
     echo "Error: " . $e->getMessage();
 }
?>

现在您可以将其称为

之类的任何功能
function mytest(){
     global $connection;
}

答案 2 :(得分:0)

老实说,最简单的方法是在函数内部设置连接,然后在其他函数中使用该函数。

示例:

error_reporting(E_ALL);
ini_set('display_errors', 1);

function dataQuery($query, $params) {
$queryType = explode(' ', $query);

// establish database connection
try {
    $dbh = new PDO('mysql:host='.DB_HOSTNAME.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    echo $e->getMessage();
    $errorCode = $e->getCode();
}

// run query
try {
    $queryResults = $dbh->prepare($query);
    $queryResults->execute($params);
    if($queryResults != null && 'SELECT' == $queryType[0]) {
        $results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
        return $results;
    }
    $queryResults = null; // first of the two steps to properly close
    $dbh = null; // second step to close the connection
}
catch(PDOException $e) {
    $errorMsg = $e->getMessage();
    echo $errorMsg;
}
}

如何在另一个功能中使用:

function doSomething() {
    $query = 'SELECT * FROM `table`';
    $params = array();
    $results = dataQuery($query,$params);
    return $results[0]['something'];
}

答案 3 :(得分:-3)

最佳做法是将$conn作为参数传递给函数。 但是如果你真的需要函数没有参数但仍然使用全局变量,那么在使用变量之前在函数中添加这一行应该可以解决这个问题:

global $conn; // I want to use the global variable called $conn
相关问题