将变量发送到函数而不是函数是否更好?

We are using a query to sort mysql results in php. I decided to use one variable and then break it into two when it reaches to query function from the front end. Bellow is the example of the code sort is equal to an example value being sent.

$sort = 'total_amount-ASC';  
$order = explode("-",$sort); 
if($order[1]=='ASC'){ 
    $query->orderAsc("'".$order[0]."'"); 
}else if($order[1]=='DESC'){ 
    $query->orderDesc("'".$order[0]."'"); 
}

Is this an acceptable way to send code from front end to a php script or should I be sending two separate variables?

If you are asking if the code is a good way to handle it, then my answer is no. Simply because it would fail several unit tests:

  • What if the order is not specified or even desired to be unspecified (suppose PHP could sort the raw results faster?)
  • What about multiple sort criteria when that need arises?
  • Is the user able to control the output case? Will 'asc' work as well as 'ASC'?

Probably a proper way to pass this would be an array,

Sort by: <select name="sort[]"> <option>City <option>State <option>Zip </select><br />
In <select name="order[]"><option value="">(none) <option value="ASC">A-Z <option value="DESC">Z-A </select>

Iterate your rows and then just sort through the field order by will always have a corresponding value even if it's blank. Very similar to the way desktop apps do it.