How can PDO be used to protect against SQL injection in PHP?
To protect against SQL injection in PHP, you can use PDO (PHP Data Objects) to prepare and execute SQL queries with bound parameters. By using prepared statements, PDO automatically escapes input data, preventing malicious SQL injection attacks.
// Establish a database connection using PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders for parameters
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the parameter values to the placeholders
$stmt->bindParam(':username', $username);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
Keywords
Related Questions
- Are there specific security measures that should be taken when allowing users to delete table entries using checkboxes in PHP?
- What are the potential pitfalls of using the original mysql extension in PHP, and why should developers consider switching to MySQLi or PDO?
- What are some PHP libraries/packages that can be used to access (remote) GIT repositories from a PHP web application?