mysqli 连接变量对所有函数可见?
mysqli connection variable visible to all functions?
我有 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 变量。我需要在 get_name 函数(以及所有函数)中包含 config.php。
是否有任何其他方法无需在所有函数中包含 config.php 即可获取 $mysqli 变量?
对函数中的变量使用全局变量。
function get_name{
global $mysqli;
$stmt = $mysqli->prepare("SELECT * FROM users WHERE user=?");
}
为此使用 class 和对象。在配置页面中写下连接变量并通过将配置页面包含在数据库 class 中,在继承的 class 中编写您的函数,然后将其传递给基于对象的函数引用。
我有 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 变量。我需要在 get_name 函数(以及所有函数)中包含 config.php。
是否有任何其他方法无需在所有函数中包含 config.php 即可获取 $mysqli 变量?
对函数中的变量使用全局变量。
function get_name{
global $mysqli;
$stmt = $mysqli->prepare("SELECT * FROM users WHERE user=?");
}
为此使用 class 和对象。在配置页面中写下连接变量并通过将配置页面包含在数据库 class 中,在继承的 class 中编写您的函数,然后将其传递给基于对象的函数引用。