What are the potential security risks of directly inserting user input into a SQL query in PHP?
Directly inserting user input into a SQL query in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to access, modify, or delete data from the database. To prevent this, you should always use prepared statements with parameterized queries to sanitize and validate user input before executing the query.
// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$results = $stmt->fetchAll();