What are the potential pitfalls of not properly sanitizing user input in a PHP database query?
If user input is not properly sanitized in a PHP database query, it can leave your application vulnerable to SQL injection attacks. This means that malicious users could potentially manipulate your database queries to access, modify, or delete data. To prevent this, always use parameterized queries or prepared statements to sanitize user input before including it in a query.
// Using prepared statements to sanitize user input in a PHP database query
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// User input
$userInput = $_POST['user_input'];
// Prepare the SQL query with a placeholder
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the sanitized user input to the placeholder
$stmt->bindParam(':username', $userInput, PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();