How can PHP developers ensure secure database queries when handling user input?
PHP developers can ensure secure database queries when handling user input by using prepared statements with parameterized queries. This approach helps prevent SQL injection attacks by separating SQL code from user input data. Developers should also validate and sanitize user input to ensure it meets the expected format and type.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query with a parameterized statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input to the parameter in the query
$username = $_POST['username'];
$stmt->bindParam(':username', $username);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Use the results as needed
foreach ($results as $row) {
echo $row['username'] . '<br>';
}
Related questions
-
move_uploaded_file file uploads security vulnerabilities
-
gettext PHP web hosting
-
validation sanitization htmlspecialchars