What are the dangers of directly inserting variables into SQL queries in PHP?

Directly inserting variables into SQL queries in PHP can lead to SQL injection attacks, where malicious SQL code is inserted into the query, potentially giving attackers access to your database. To prevent this, you should use prepared statements with parameterized queries, which separate the SQL query logic from the user input.

// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

$username = $_POST['username']; // User input
$stmt->bindParam(':username', $username);
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();