What are the potential pitfalls of using direct variable insertion in SQL queries in PHP?
Direct variable insertion in SQL queries in PHP can lead to SQL injection attacks if user input is not properly sanitized. To prevent this, it is recommended to use prepared statements with parameterized queries. This helps separate the SQL query logic from the user input, making it safer and more secure.
// Using prepared statements with parameterized queries to prevent SQL injection
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the user input to the placeholder
$stmt->bindParam(':username', $username);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();