欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > 数据库 >内容正文

数据库

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

发布时间:2025/3/20 数据库 60 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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是否不是全局的?

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

总结

以上是生活随笔为你收集整理的php5的mysqli函数第二个参数,关于php:我应该将$ mysqli变量传递给每个函数吗?的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。