What are the best practices for handling mysqli connections and queries in PHP?
When handling mysqli connections and queries in PHP, it is important to properly establish and close connections to the database to avoid resource leaks. It is also recommended to use prepared statements to prevent SQL injection attacks and improve performance.
// Establishing a mysqli connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Using prepared statements to execute a query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
// Fetching results
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Closing the statement and connection
$stmt->close();
$mysqli->close();