php5的mysqli函数第二个参数,关于php:我应该将$ mysqli变量传递给每个函数吗?

我从mysql_ *传递到面向对象的mysqli时遇到了一些问题。

我的index.php文件的结构类似于包括两个文件:

include('connect.php');

include('function.php');

connect.php文件包含:

$mysqli = new mysqli("localhost","root","test","test");

if (mysqli_connect_errno($mysqli)) {

printf("Connection failed: %s

", mysqli_connect_error());

exit();

}

?>

在function.php文件中,有一个名为showPage的函数,该函数不带任何参数,但使用$ mysqli连接,例如...

$result = $mysqli -> query("SELECT * FROM $table ORDER BY ID DESC"); // Seleziono tutto il contenuto della tabella

我无法管理它而无法将$ mysqli变量传递给函数,但是当我使用mysql_ *不推荐使用的函数时,这不是必需的!

我能理解为什么吗,什么是解决此问题的最佳方法?

@Wired删除密码后,然后可能仍然使用它

如前所述,它是一个旧数据库(也在本地),我正在对其进行测试。 但是我还是不希望我的数据写在网上= P还是让我感到困扰

用户定义的函数在PHP中具有自己的变量范围。您需要将$mysqli作为参数传递给该函数,或者使用global $mysqli启动该函数。

在"变量作用域"页面上,给出了确切的问题作为示例:

However, within user-defined functions a local function scope is

introduced. Any variable used inside a function is by default

limited to the local function scope. For example, this script will not

produce any output because the echo statement refers to a local

version of the $a variable, and it has not been assigned a value

within this scope. You may notice that this is a little bit different

from the C language in that global variables in C are automatically

available to functions unless specifically overridden by a local

definition. This can cause some problems in that people may

inadvertently change a global variable. In PHP global variables must

be declared global inside a function if they are going to be used in

that function.

$a = 1; /* global scope */

function test()

{

echo $a; /* reference to local scope variable */

}

test();

?>

全局变量是邪恶的xD,但是您的答案是最好的。 我习惯了C,这就是为什么我无法做到这一点。 我更喜欢每次都将变量作为参数传递。 谢谢。

在这种情况下,全局变量是完全有效且可理解的设计模式。 毕竟,数据库连接对象是应用程序中的全局对象。 但是,我会将您的mysqli对象包装在您自己的用户创建的对象中,并在全局范围内使用此对象,因为这将使您能够灵活地根据需要进行改进/升级,而不必对应用程序进行大量更改。

您还可以使用连接池,值得一试。

$mysqli = new mysqli('p:localhost', 'username', 'password', 'db_name');

cannot manage it to work without passing to the function the $mysqli variable, but this was not necessary when I used mysql_* deprecated functions!

那是不正确的。即使在旧的mysql_*函数中,如果您需要指定与哪个数据库连接有关,实际上也必须传递链接标识符,例如:

$result = mysql_query($sql, $link);

此示例还显示了,您也必须传递$result。如果确实遗漏了$link参数:

$result = mysql_query($sql);

mysql扩展确实在内部寻找上次使用的连接。如果没有找到,它将使用php.ini中设置的参数创建一个新的。这只是为了您提供信息,以便更好地了解过去的原因和工作方式。

经过更好的搜索后,我找到了答案,它适用于可能需要它的任何人:

PHP更改为mysqli。 mysqli_connection是否不是全局的?

这就是我需要的答案。无论如何,感谢所有帮助我的人

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值