How can SQL Injection attacks be prevented when using PHP for database interactions?
SQL Injection attacks can be prevented in PHP by using prepared statements and parameterized queries. This method separates SQL code from user input, preventing malicious input from being executed as SQL commands.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement using placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
Related questions
-
PHP function return
-
PHP URL parameters GET method
-
try-catch error_reporting exception handling