【发布时间】:2014-05-09 18:26:07
【问题描述】:
一个 PHP 页面说,common.php 包含该行,以及一些其他 PHP 变量和代码。
$mysqli=new MySQLi("localhost", "username", "password");
所以在其他页面中,我简单地包含了这个 common.php,使用require_once("common.php") 并使用$mysqli 变量进行所有与数据库相关的操作。一切正常。在随机情况下,我需要在 PHP 页面中创建一个函数,例如,
function checking($some_data)
{
// Using $mysqli check $some_data with database here and return 0 or 1 based on database operations
// Here it says $mysqli is not defined.
}
$somevariable=$mysqli->prepare($query); // This is outside the function and works fine
$result=checking($some_data); // This does not work and says $mysqli not defined.
我尝试在函数中添加global $mysqli。但是如果我这样做,MySQLi 连接就不能用于那个。在每个带有连接参数的函数中定义$mysqli,听起来很疯狂。什么可能是简单的解决方案?
【问题讨论】:
-
要么使用函数内部的参数来传递
$mysqli,要么添加global $mysqli;从全局范围中获取它。如果您在另一个函数中打开连接,您还需要将该行添加到函数中,以便在全局范围内创建$mysqli。