如何使用函数内部函数而不通过?

时间:2016-12-18 07:14:15

标签: php mysql function

我正在尝试在函数内部使用db连接参数,我试图将其全局化,但它不起作用。

$host = 'localhost';
    $username = 'b**s';
    $password = '1******m';
    $dbname = 'b*********e';        
    $connection = new mysqli($host, $username, $password, $dbname);
    if ($connection->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

当我执行查询时它返回错误,因为我没有在函数内传递$connection参数。

function insertData(){
        {......}
        if($connection->query($sql)){           
            $response['success'] = 'User record successfully added!'; 
        }
    } 

任何人都可以指导我最好使用什么而不传递函数内部参数。如果有人指导我,我很感激。

2 个答案:

答案 0 :(得分:1)

在你的功能中,你应该做一些像

这样的事情
global $connection;

然后在下面使用

if($connection->query($sql)){           
      $response['success'] = 'User record successfully added!'; 
 }

这在手册中有详细记载,我建议你去看看。

答案 1 :(得分:1)

创建数据库类并按对象访问

<?php

class Database {

    private static $db;
    private $connection;

    private function __construct() {
        $this->connection = new MySQLi(/* credentials */);
    }

    function __destruct() {
        $this->connection->close();
    }

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

?>

然后在我需要的地方使用$db = Database::getConnection();

相关问题