What are the common pitfalls when using mysqli in object-oriented PHP for database connections?
One common pitfall when using mysqli in object-oriented PHP for database connections is not properly handling errors. It's important to check for errors after each database operation and handle them appropriately to prevent unexpected behavior. Another pitfall is not using prepared statements, which can leave your application vulnerable to SQL injection attacks. Lastly, make sure to close the database connection when it's no longer needed to avoid resource leaks.
// Example of handling errors and using prepared statements with mysqli
// Create a new mysqli connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check for connection errors
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a statement with placeholders
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind parameters to the statement
$stmt->bind_param("s", $username);
// Execute the statement
$stmt->execute();
// Handle errors
if ($stmt->error) {
die("Error executing statement: " . $stmt->error);
}
// Close the statement
$stmt->close();
// Close the connection
$mysqli->close();