How can one properly sanitize and validate variables used in SQL queries in PHP to prevent SQL injection attacks?
To properly sanitize and validate variables used in SQL queries in PHP to prevent SQL injection attacks, you can use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious input from altering the query structure.
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the sanitized user input to the parameter
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$stmt->bindParam(':username', $username);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Keywords
Related Questions
- How can the use of exit() affect the overall security and maintainability of PHP scripts?
- In what situations would it be more efficient to store data in a format other than plain text within a txt file?
- What potential issues may arise when trying to add a directory with subdirectories to a repository using svn_add() in PHP?