How can user input be securely incorporated into SQL queries in PHP?
When incorporating user input into SQL queries in PHP, it is crucial to use prepared statements with parameterized queries to prevent SQL injection attacks. This involves binding parameters to placeholders in the query, which ensures that user input is treated as data rather than executable code. By using prepared statements, the input is sanitized and escaped automatically, making the application more secure.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with a placeholder
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();