How can prepared statements be used to prevent SQL injection in PHP when querying a database?
SQL injection can be prevented in PHP by using prepared statements. Prepared statements separate the SQL query from the user input, which prevents malicious SQL code from being executed. This is done by sending the SQL query and parameters separately to the database, ensuring that user input is treated as data rather than executable code.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input to the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
Related Questions
- How can a local mail server without a domain be set up to send emails to external addresses like @t-online.de?
- In what ways can PHP developers optimize the performance and functionality of a photo voting script in PHP-Nuke by serializing and storing array data in hidden form fields, and what considerations should be made for non-logged-in users accessing the voting feature?
- Are there any best practices for handling file paths with spaces in PHP, especially on Windows systems?