What potential security risks are associated with directly using user input in database queries in PHP scripts?
Directly using user input in database queries in PHP scripts can lead to SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To prevent this, it is important to sanitize and validate user input before incorporating it into queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL query logic from the user input, making it impossible for attackers to inject malicious code.
// Using prepared statements to prevent SQL injection
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// User input
$userInput = $_POST['input'];
// Prepare a SQL query using a placeholder
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the user input to the placeholder
$stmt->bindParam(':username', $userInput);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();