mysqli连接变量对所有函数可见吗?

时间:2015-04-12 10:14:00

标签: php mysqli

我有config.php:

$mysqli = new mysqli($hostname, $user, $pass, $bd);

我在所有网站页面中都包含此config.php。 例如

的index.php

include("config.php");
include("functions.php");
...
在functions.php中的

我有这样的函数:

function get_name{
 $stmt = $mysqli->prepare("SELECT * FROM users WHERE user=?");
}

我的问题是,函数get_name无法看到$ mysqli var。我需要在get_name函数(以及所有函数)中包含config.php。

有没有其他方法可以获得$ mysqli变量而无需在所有函数中包含config.php?

2 个答案:

答案 0 :(得分:1)

对函数中的变量使用全局。

function get_name{
    global $mysqli;
     $stmt = $mysqli->prepare("SELECT * FROM users WHERE user=?");
    }

答案 1 :(得分:0)

为此使用类和对象。在配置页面中记下连接变量&通过在数据库类中包含配置页面,在继承的类中编写函数,然后在基于对象的函数引用中传递它。