如何在PHP文件之间传递数据库连接实例而不重新声明它 [英] How to pass database connection instance between PHP files without redeclaring it

查看:57
本文介绍了如何在PHP文件之间传递数据库连接实例而不重新声明它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 中创建了一个数据库连接实例,例如:

I have created a database connection instance in PHP like:

$mysqli = mysqli_connect("localhost", "root", "blabla", "blabla");

我需要将此数据库连接传递给其他 PHP 文件,因为我有一个 HTML 表单,该表单首先将数据插入数据库,然后转到检索数据的 PHP 页面.

I need to pass this database connection to other PHP files, since I have an HTML form that first inserts data into a database and then it goes to a PHP page that retrieves data.

我知道我不能每次都实例化数据库连接但我不知道该怎么做,因为我对OO PHP不是很熟悉.

I know that I must not instantiate the database connection each time but I do not know how to do it, because I am not so familiar with OO PHP.

推荐答案

您可以只命名一个文件 connection.php 并存储您的行以连接到数据库.然后你可以像这样包含你的文件:

You can just name a file connection.php and store your line for connection to database. Then you can include your file like this :

require_once('connection.php');

这将是 connection.php 的内容:

This will be the content of connection.php :

$mysqli = mysqli_connect("localhost", "root", "blabla", "blabla");

这样,您的文件将永远不会加载两次.

And then this way, your file will never load twice.

这篇关于如何在PHP文件之间传递数据库连接实例而不重新声明它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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