Ofcourse this is not working, you can't include PHP blocks inside PHP blocks.
What you want to end up with is a single string containing the SQL query.
This does not mean you have to create the string all at once, you can create a string and append to it later, like this:
$query="SELECT * FROM table WHERE 1=1 ";
if ($something=$something_else)
{
$query .= " AND something=sometheing else";
};
$query .= " ORDER BY nothing";
echo $query;
Notice how you can use an IF statement to conditionally add text to your query.
Also notice that I have put a "WHERE 1=1" as the first condition in the statement.
"Where 1=1" is ofcourse allways true. It is only in there so I can use "AND" for the rest of my conditions. Otherwise, I'd have to put extra code in each IF statement to check if it should put WHERE or AND. This way it's allways AND.
And finally, note the use of spaces before each added statement!