What are some common approaches to sorting and limiting results in PHP MySQL queries based on user input values?

When users interact with a website or application, they often want to sort and limit the results of a query based on their preferences. This can be achieved by dynamically constructing the SQL query in PHP based on the user input values for sorting and limiting the results.

// Assume $sortBy and $limit are user input values
$sortBy = $_GET['sortBy'];
$limit = $_GET['limit'];

// Construct the SQL query based on user input
$sql = "SELECT * FROM table_name";

if ($sortBy) {
    $sql .= " ORDER BY $sortBy";
}

if ($limit) {
    $sql .= " LIMIT $limit";
}

// Execute the SQL query and process the results
$result = mysqli_query($connection, $sql);

while ($row = mysqli_fetch_assoc($result)) {
    // Process each row of the result
}