How can PHP developers protect against SQL Injection in their scripts?
SQL Injection can be prevented by using prepared statements with parameterized queries in PHP. This technique separates the SQL query logic from the data being passed into it, preventing malicious SQL code from being injected into the query.
// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with parameters
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
// Bind parameters to the statement
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
// Execute the statement
$stmt->execute();
Keywords
Related Questions
- What best practices should be followed when using gethostbyaddr function in PHP scripts to prevent errors or delays in execution?
- How can session variables impact user login/logout functionality in PHP?
- How can PHP be used to dynamically sort a table via MySQL without using a table sorter with JavaScript?