What are the potential security risks of using user input directly in a SQL query in PHP?
Using user input directly in a SQL query in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to access or modify sensitive data. To prevent this, you should always use prepared statements with parameterized queries in PHP to sanitize and validate user input before executing the SQL query.
// Sample code to prevent SQL injection using prepared statements
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a SQL query using a parameterized statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the user input after sanitizing and validating it
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
// Execute the prepared statement
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();