What are the potential security risks associated with directly including user input in SQL queries in PHP?
Directly including user input in SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to access, modify, or delete data in the database. To prevent this, you should always sanitize and validate user input before including it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL code from the user input.
// Example of using prepared statements to prevent SQL injection
// Assuming $conn is your database connection
$user_input = $_POST['user_input']; // User input from a form
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();
// Fetch results, loop through them, etc.
$stmt->close();
$conn->close();