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 functions or libraries that can assist in handling CSV imports with complex data structures?
- What potential issues can arise when converting dates in PHP, especially for dates before 1970?
- How can the use of the header() function in PHP affect the handling of cookies on a webpage?