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_sort = "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…
Then your query statement would be such as…
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.