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 you determine if a word stored in a variable is contained in a sentence stored in another variable in PHP?
- What are the best practices for calculating time differences and points per day in PHP, especially when dealing with datetime data types?
- How can timestamps be effectively used in PHP to track and manage time-sensitive actions, such as resetting database entries after a specific time period?