How can SQL-Injection be prevented in PHP applications?
SQL-Injection can be prevented in PHP applications by using prepared statements with parameterized queries instead of directly interpolating user input into SQL queries. This helps to separate the SQL code from the user input, making it impossible for malicious users to inject SQL code into the query.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query using a parameterized statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input to the parameter
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();