How can PHP developers prevent SQL injection when querying databases?
To prevent SQL injection when querying databases in PHP, developers should use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious code from being injected into the query.
// Connect 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");
// Bind the parameter values
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
Related questions
-
XSS prevention PHP security Content visibility
-
OOP inheritance encapsulation
-
dropdown menu links limitations