What is the best practice for handling user input in PHP to prevent SQL injection when sorting a table?
To prevent SQL injection when sorting a table in PHP, the best practice is to use prepared statements with parameterized queries. This ensures that user input is properly sanitized and treated as data rather than executable SQL code.
// Assuming $sortColumn is the user input for the column to sort by
// Assuming $sortOrder is the user input for the order (ASC or DESC)
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with placeholders for user input
$stmt = $pdo->prepare("SELECT * FROM mytable ORDER BY $sortColumn $sortOrder");
// Bind parameters
$stmt->bindParam(':sortColumn', $sortColumn);
$stmt->bindParam(':sortOrder', $sortOrder);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();