What are the best practices for handling user input in PHP to prevent SQL-Injection?
To prevent SQL-Injection in PHP, it is essential to sanitize and validate user input before using it in database queries. The best practice is to use prepared statements with parameterized queries, which separate the SQL code from the user input, preventing malicious code from being executed.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Sanitize and validate user input
$userInput = $_POST['input'];
$filteredInput = filter_var($userInput, FILTER_SANITIZE_STRING);
// Prepare a statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $filteredInput);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Related Questions
- Is it better to create a new function or integrate functionality into an existing one when iterating through multiple database entries in PHP?
- What are the differences between ereg and eregi functions in PHP, and when should each be used?
- What are the potential pitfalls of using strtotime with language-specific date formats in PHP?