1

我尝试将 mysqli 连接脚本放入一个 php 函数中,各种 php 文件可以调用该函数来连接到数据库。我创建了以下功能:

public function connectToDatabase() {

    $con = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);

    echo "<br><br>";

    if (mysqli_connect_errno($con)) {
        echo "Failed to connect to MySQL:" . mysqli_connect_error();
    } else {
        echo "Connection successful";
    }

    return $con;
}

然后我使用(已包含上述文件)从另一个文件中调用该函数:

$con = connectToDatabase();

然而,虽然顶部函数中的代码工作正常,但在变量 $con 中传递连接似乎不起作用。我突然想到,当它到达 return 语句时,连接会自动关闭。是这样吗?如果是这样,我该如何阻止它?

非常感谢

4

1 回答 1

1

虽然您的问题已在评论中得到解答,但最好将您的连接构建为 Singleton 类,这样您就不会在整个代码中打开连接的多个实例:

class DatabaseConnection {

    const HOST     = 'localhost';
    const USERNAME = 'not_root';
    const PASSWORD = 'not_blank';
    const NAME     = 'your_db';

    private static $_instance;

    // Private constructor prevents instantiation
    private function __construct() {
    }

    public static function getInstance() {
        if (!self::$_instance) {
            self::$_instance = mysqli_connect(self::HOST, self::USERNAME, self::PASSWORD, self::NAME);
            if (mysqli_connect_errno(self::$_instance)) {
                throw new Exception("Failed to connect to MySQL:" . mysqli_connect_error());
            }
        }
        return self::$_instance;
    }
}

然后,这样称呼它:

try {
    $con = DatabaseConnection::getInstance();
} catch (Exception $e) {
    // Handle exception
    echo $e->getMessage();
}
于 2013-06-16T10:06:01.017 回答