What potential pitfalls can occur when using MySQL queries in PHP for database operations?
One potential pitfall when using MySQL queries in PHP is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, always use prepared statements with parameterized queries to ensure that input values are treated as data, not executable code.
// Using prepared statements to prevent SQL injection
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement with a placeholder for the 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();
// Fetch the results
$result = $stmt->get_result();
// Process the results as needed
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and the database connection
$stmt->close();
$mysqli->close();