How can SQL injection be avoided when processing user input in PHP?
SQL injection can be avoided in PHP by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input data, preventing malicious SQL code from being executed. By binding parameters to the query, the database engine can distinguish between code and data, ensuring safe execution.
// 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');
// Bind the user input to the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
Related Questions
- What are some common error messages that may arise when working with file handling functions like fopen(), fwrite(), and fclose() in PHP, and how can they be resolved?
- How can sessions be used to maintain user login status across multiple pages in a PHP application?
- In what scenarios would using absolute paths in PHP be more beneficial than relative paths?