在使用数据库的每个函数中是否都需要php mysql连接? [英] Do I need a php mysql connection in each function that uses database?

查看:217
本文介绍了在使用数据库的每个函数中是否都需要php mysql连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个php restful API,目前每个函数中都有数据库连接信息.

I am creating a php restful API and currently I have the database connection information in each function.

//Connect To Database
    $hostname=host;
    $username=username;
    $password=password;
    $dbname=dbname;

    mysql_connect($hostname, $username, $password) OR DIE('Unable to connect to database! Please try again later.');
    mysql_select_db($dbname);
mysql_query($sqlApiAccess) or die('Error, insert query failed');

执行此操作的最佳方法是什么,每个php文件可以建立一个数据库连接吗?还是我需要针对使用数据库的每个函数执行此操作.

What is the best way of doing this, Can I have one database connection per php file? Or do I need to do it per function that uses the database.

推荐答案

创建config.php并添加代码:

Create a config.php And add the code:

config.php:

$hostname = 'host';
$username = 'username';
$password = 'password';
$dbname   = 'dbname';

$conn = mysqli_connect($hostname, $username, $password) OR die('Unable to connect to database! Please try again later.');
mysqli_select_db($conn, $dbname);

然后在您希望使用mysql的任何文件中,添加以下内容:

Then in any file you wish to use mysql, add the following:

script2.php

<?php
require_once 'config.php';

mysqli_query($sqlApiAccess) or die('Error, insert query failed');
?>

这篇关于在使用数据库的每个函数中是否都需要php mysql连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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