What are the best practices for handling MySQL database connections and queries in PHP scripts to avoid errors?
When handling MySQL database connections and queries in PHP scripts, it is important to properly establish and close connections to avoid errors such as connection leaks or exceeding the maximum connection limit. Additionally, using prepared statements can help prevent SQL injection attacks and improve query performance.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform a query using prepared statements
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $value);
$value = "example";
$stmt->execute();
$result = $stmt->get_result();
// Process the query results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the connection
$stmt->close();
$conn->close();