What is the best practice for handling database connections in PHP scripts?
The best practice for handling database connections in PHP scripts is to establish a connection to the database only once and reuse that connection throughout the script to improve performance and reduce resource usage. This can be achieved by creating a separate PHP file for database connection and including it in other PHP scripts where database operations are needed.
// database_connection.php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
```
```php
// other_script.php
include 'database_connection.php';
// Use $conn for executing database queries
$query = "SELECT * FROM table";
$result = $conn->query($query);
// Process query results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Process each row
}
} else {
echo "0 results";
}
// Close connection
$conn->close();