Do I need a php mysql connection in each function that uses database?

mysql, php

Solution

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);

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');
?>

Problem

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'); ``` 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.

Original source

Related problems