What are the best practices for handling database connections in PHP when retrieving data from multiple tables?
When retrieving data from multiple tables in PHP, it is best practice to establish a single database connection and reuse it throughout the script to minimize resource usage. This can be achieved by creating a separate function to handle the database connection and then calling this function whenever data retrieval is needed from different tables.
// Function to establish a database connection
function connectToDatabase() {
$host = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'database_name';
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
// Example usage of the connectToDatabase function
$conn = connectToDatabase();
// Query to retrieve data from multiple tables
$sql = "SELECT * FROM table1 JOIN table2 ON table1.id = table2.id";
$result = $conn->query($sql);
// Process the retrieved data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Process each row of data
}
} else {
echo "No results found";
}
// Close the database connection after data retrieval is complete
$conn->close();
Related questions
-
unlink function PHP file deletion
-
cURL external websites communication
-
cUrl PHP broken links