What are common pitfalls in querying MySQL data in PHP and how can they be avoided?
Common pitfalls in querying MySQL data in PHP include not properly sanitizing user input, not handling errors effectively, and not closing database connections after querying. To avoid these pitfalls, always use prepared statements to prevent SQL injection, implement error handling to catch and handle any database errors, and remember to close the database connection after querying.
// Example of querying MySQL data in PHP with prepared statements and error handling
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check for connection errors
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a SQL statement with a placeholder for user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
// Bind the user input to the placeholder
$stmt->bind_param("s", $username);
// Execute the statement
$stmt->execute();
// Get the result set
$result = $stmt->get_result();
// Fetch the data
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();