What are best practices for dynamically generating SQL queries in PHP based on user input?

When dynamically generating SQL queries in PHP based on user input, it is important to sanitize and validate the user input to prevent SQL injection attacks. One way to achieve this is by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, making it safer and more secure.

// Sample code for dynamically generating SQL queries based on user input using prepared statements

// Assume $conn is the database connection object

// Sanitize and validate user input
$userInput = $_POST['user_input'];
if (!empty($userInput)) {
    // Prepare the SQL query
    $stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name = ?");
    
    // Bind parameters
    $stmt->bind_param("s", $userInput);
    
    // Execute the query
    $stmt->execute();
    
    // Fetch results
    $result = $stmt->get_result();
    
    // Process the results
    while ($row = $result->fetch_assoc()) {
        // Do something with the data
    }
    
    // Close the statement
    $stmt->close();
}