Mysql connect code as a function in php

Hello,

I have a couple of questions.

  1. For every php file (in the site i am making) should i initiate a mysql connection each time I interact with the db. After each interaction i am closing the connection. Can’t i just have one connection made and use that?

  2. I created a functions.php file in which i have the mysql connection code. Do i have to return the $conn variable if successful connection is made? In the main file, I did a include functions.php but I am unable to run a query in the db.

Functions.php

function connectRentalDB(){
$db_address = 'localhost';
$username = '**********';
$password = '********';
$dbname = "rental";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_error()) {
     die("Database connection failed: " . mysqli_connect_error());
}
return $conn;
}


?>

and my main file is

<?php include 'functions.php';?>

<html>

<head><title>My rental management app</title>

<body>

<?php

$conn1 = connectRentalDB();

echo "Welcome to the app. Let us keep this simple and begin with a framework"

$sql = "select username from useraccess";

$result = mysqli_query($conn1,$sql);

mysqli_num_rows($result);

mysqli_close($conn1);

?>

</body>

</head>

</html>


~

Please help me.
ranjit

Open the connection once. Php will automatically close the connection when it is done so no need for you to manually close it.

Yes, so that you have a reference to the database connection to use in your future queries. The other way would be a global variable for the connection, but that’s not a good thing IMO.

In what way are you unable? Do you get error messages, in which case what are they?

This bit of code:

$result = mysqli_query($conn1,$sql);

mysqli_num_rows($result);

doesn’t make a lot of sense - in particular the second line. You should really assign the return from mysqli_num_rows() to a variable, or echo it.

In this code:

function connectRentalDB(){
$db_address = 'localhost';
$username = '**********';
$password = '********';
$dbname = "rental";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);

where does $servername come from? I think it should be the variable you have called $db_address.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.