PHP更改为mysqli。 mysqli_connection不是全局的吗? [英] PHP changing to mysqli. Is the mysqli_connection not global?

查看:116
本文介绍了PHP更改为mysqli。 mysqli_connection不是全局的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始一个新的PHP项目,我想是时候遵循php建议,停止使用mysql和swith来代替mysqli。但是这给了我一个问题。



通常我的设置是这样的



Index.php文件,文件我有2个需要的语句。一个调用db.php文件,另一个调用functions.php文件。到目前为止这样好。



在functions.php文件中,有许多不同的函数在整个主页中使用,其中许多函数都使用SQL。
使用php旧的mysql API这没有问题,但它接近新的mysqli api不允许从包含文件中使用连接???



例如在我的db.php中,我有connect语句。 $ db = mysql_connect(*******);
在我的function.php中,我有 mysql_query(*** ***),它完美无缺。



但是,如果我将db.php更改为 $ db = mysqli_connect (*****);
然后在我的function.php文件中,我无法调用 mysqli_query(***)。 (我也测试了面向对象,但它给了我同样的问题)。

那么如何解决这个问题呢?
php是否期待我将mysqli_connect语句放在使用sql语句的每个文件的开头?

解决方案< /是的,MySQLi是面向对象的,你需要将 $ db 对象传递给需要数据库连接的函数。过程替代方案还需要 $ db 对象工作。这是为了您自己的利益,因为隐式的全局连接(实际上是任何形式的全局状态)都是不好的做法。 mysql扩展允许隐式连接并不好。


I have just started a new PHP project and I was thinking it's time to follow php suggestion and stop using mysql and swith to mysqli instead. But this gave me a problem.

Normaly my setup is like this

Index.php file and inside this file I have a 2 require statements. One that calls for the db.php file and one other to call a functions.php file. So far so good.

In the functions.php file a have a lot of different functions that is used all over the homepage and many of these are using SQL. With php old mysql API this was no problem but it seams that the new mysqli api don't allow connections to be used from included files???

For example in my db.php I have the connect statement. $db = mysql_connect(*******); And in my function.php I have mysql_query(******) and it works perfect.

But if I change the db.php to $db = mysqli_connect(*****); Then in my function.php file I can't call the mysqli_query(***). (I have also tested object oriented but it gives me the same problem).

So how to get around this problem? Is php expecting me to put the mysqli_connect statement in the beginning of every file that uses sql statements?

解决方案

Yes, MySQLi is object oriented and you need to pass around the $db object to the functions that need a database connection. The procedural alternatives also require the $db object to work. This is for your own good, as implicit global connections (actually: global state in any form) are bad practice. That the mysql extension allowed implicit connections was not good to begin with.

这篇关于PHP更改为mysqli。 mysqli_connection不是全局的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆