What are common mistakes made when querying a database in PHP?
Common mistakes when querying a database in PHP include not sanitizing user input, not using prepared statements to prevent SQL injection attacks, and not properly handling errors. To solve these issues, always sanitize user input using functions like mysqli_real_escape_string, use prepared statements with placeholders for dynamic data, and implement error handling to catch and handle any database errors.
// Example of querying a database in PHP with prepared statements and error handling
// Establish a connection to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');
// Check for connection errors
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Prepare a SQL statement with a placeholder for dynamic data
$stmt = $connection->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Sanitize user input
$username = mysqli_real_escape_string($connection, $_POST['username']);
// Execute the query
$stmt->execute();
// Handle any errors
if ($stmt->error) {
die("Query failed: " . $stmt->error);
}
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$connection->close();