What are the best practices for handling MySQL connections and queries in PHP to ensure smooth functionality?
When working with MySQL connections and queries in PHP, it is important to properly handle connections to avoid potential issues like memory leaks or connection errors. One best practice is to establish a connection to the database only when needed and close it as soon as possible after executing queries. Additionally, using prepared statements can help prevent SQL injection attacks and improve performance.
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform queries using prepared statements
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process data
}
// Close the connection
$stmt->close();
$conn->close();