How can SQL injection be prevented when executing database queries in PHP?
SQL injection can be prevented in PHP by using prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, the database system can differentiate between code and data, effectively mitigating the risk of SQL injection attacks.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
// Bind parameters to placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
// Execute the statement
$stmt->execute();
Related Questions
- How can one change the background color in an input field using PHP?
- Are there alternative methods or functions in PHP that can be used instead of header(location: $url) to redirect users to a different URL?
- What is the best method to retain the value of a variable like $Programm even after a page refresh in PHP?