【问题标题】:Make MySQLi conenction variable available inside functions too [duplicate]使 MySQL 连接变量在函数内部也可用 [重复]
【发布时间】: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

标签: php mysqli


【解决方案1】:

在这种情况下,在函数内部添加global $mysqli 会很有效。如果它不起作用,那么您在函数或查询中的某个地方出错(可能是)。

function function_name_here($arguement_variable_here)
{
  global $mysqli;
  $mysqli->query($query);
}

并确保在函数定义之前包含依赖文件 - common.php。如果 include/require 在函数定义之下完成,在某些情况下可能不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2017-12-22
    • 2021-09-12
    • 2019-03-27
    • 2018-06-14
    • 2012-06-18
    相关资源
    最近更新 更多