How can SQL injection be prevented in PHP when querying a database?
SQL injection can be prevented in PHP when querying a database by using prepared statements with parameterized queries. This approach allows the database to distinguish between SQL code and data, preventing malicious SQL injection attacks.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
// Prepare a statement with parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind parameters
$stmt->bindParam(':username', $_POST['username']);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
Related Questions
- Are there any specific PHP frameworks or libraries that could simplify the process of developing a help system with search functionality?
- Are there any best practices to follow when dealing with line breaks in PHP variables?
- What are the benefits of using the mysqli extension over the mysql extension in PHP?