在不同的PHP页面中使用相同的MySQL连接 [英] Using same MySQL Connection in different PHP pages

查看:228
本文介绍了在不同的PHP页面中使用相同的MySQL连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的大学项目在PHP中创建一个简单的Web应用程序。我使用MySQL数据库。

I am creating a simple Web Application in PHP for my college project. I am using the MySQL database.

我连接到login.php中的数据库。连接后我将连接分配给$ _SESSION [conn],然后重定向到main.php。

I connect to the database in login.php. After connection I assign the connection to $_SESSION["conn"] and then redirect to main.php.

在main.php中我写$ conn = $ _SESSION [ conn]。但是$ conn中的连接不起作用。

In main.php I write $conn = $_SESSION["conn"]. But the connection in $conn does not work.

我认为login.php脚本结束后,连接被关闭。所以我尝试使用mysql_pconnect而不是mysql_connect,但是也不工作。

I thought that as the login.php script ends, the connection gets closed. So I tried using mysql_pconnect instead of mysql_connect but that too does not work.

我知道我可以重新连接到每个PHP文件中的数据库。但我不想这样做。我想在所有PHP文件中使用相同的连接。

I know I can reconnect to the database in every PHP file. But I don't want to do this. I want to use the same connection in all PHP files.

推荐答案

连接调用在一个单独的文件,如db.php,然后从每个脚本需要它。例如,将连接放在db.php中:

Instead of saving the DB connection in a session you should make the connection calls in a separate file such as db.php and then require it from each of your scripts. For example, place your connection in db.php:

mysql_connect('...', '...', '...');
mysql_select_db('...');

,然后将其放入login.php:

and then bring it in in login.php:

require('db.php');
$res = mysql_query('...');

然后,您可以对需要访问数据库的每个PHP文件执行相同操作,必须在一个文件中更改您的数据库访问凭据。

You can then do the same for each PHP file that needs access to the DB and you'll only ever have to change your DB access credentials in one file.

这篇关于在不同的PHP页面中使用相同的MySQL连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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