Are there any best practices for structuring PHP code to handle dynamic query building based on user input?
When building dynamic queries based on user input in PHP, it is important to sanitize and validate the input to prevent SQL injection attacks. One best practice is to use prepared statements with parameterized queries to securely handle user input and build dynamic queries.
// Sample code snippet for dynamically building a query based on user input
// Assuming $userInput is the user input for filtering
$userInput = $_GET['user_input'];
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
// Prepare the base query
$query = "SELECT * FROM my_table WHERE 1";
// Check if user input is provided and add it to the query
if (!empty($userInput)) {
$query .= " AND column_name = :user_input";
}
// Prepare the statement
$statement = $pdo->prepare($query);
// Bind parameters if user input is provided
if (!empty($userInput)) {
$statement->bindParam(':user_input', $userInput);
}
// Execute the query
$statement->execute();
// Fetch the results
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
// Output the results
foreach ($results as $result) {
echo $result['column_name'] . "<br>";
}