Passing variable in function
This is for a sorting script. I want to order my posts by votes. I'm using an if-statement in a function to check what order by was selected and display posts according to that.
The following function inserts data in my query.
function vote_orderby( $orderby )
{
global $vote_sort;
if( $vote_sort == "most_voted") {
// order by most votes
return "votes DESC"; //inserts into query
}
// return default order by if no votes
return $orderby;
}
HTML
$vote_so开发者_如何学Pythonrt = "most_voted"; //should be picked up by function
..function
..loop
I want to generate,
$query = "SELECT * FROM posts ORDER BY votes DESC";
But posts are ordered by date. It works however without the if-statement, this ensures that I have no MYSQL errors.
How is it possible to pass the $vote_sort
value into the function?
Note: I'm aware of the SQL injection risk, I will filter everything soon.
To answer your comment and expand on Michael's solution above, here is what you might want to do...
function vote_orderby($orderby) {
switch($orderby) {
// Sort by most votes
case 'most_voted': $sort = 'votes DESC'; break;
// Sort by least votes
case 'least_voted': $sort = 'votes ASC'; break;
// Default to most votes if does not match any other option
default: $sort = 'votes DESC'; break;
}
return $sort; // Return query statement
}
Then your query statement would be such as...
$sortby = $_GET['sort']; // However you want to get the way to sort
// If $sortby is empty, it will default to most_voted via function
$order = vote_orderby($sortby);
$query = "SELECT * FROM posts ORDER BY ".$order;
This is more of a permanent way of coding the system and prevent people to inject your MYSQL query and minor mistakes will not result in the future.
I have coded many similar systems in the past and this is one of the best ways to go.
You probably want something like this:
function vote_orderby( $orderby='most_voted' ) {
if( $orderby == "most_voted") {
// order by most votes
return "votes DESC"; //inserts into query
}
// return default order by if no votes
return $orderby;
}
In your query you want something simular to this
// this will give you the default;
$orderby = vote_orderby();
$query = 'SELECT * FROM posts ORDER BY ' . $orderby;
Or
// this will give you the name;
$orderby = vote_orderby('NAME DESC');
$query = 'SELECT * FROM posts ORDER BY ' . $orderby;
But you might just want to set a variable to the sort method and pass that into your query. Doing this in a function is a bit of a overkill or you could just add the whole query inthere and return the right one.
精彩评论