How to make ORDER BY with information that may vary?

1

I'm getting a list of articles from a database and I want to have on page one tool that allows me to list them by date order that were written or in alphabetical order.

Here I have my bank reading function:

$sel = DBRead('artigos', null ,'*', 'ORDER BY data ASC');

If I leave data the listing is made starting with the oldest post, if I change to nome the listing is made alphabetically.

I built a form in HTML with a "select" and two "options" inside and through the POST method I get the value of one of these     "option's" and put in the variable $mudanca .

But if I put the variable in the read function it gives error:

$sel = DBRead('artigos', null ,'*', 'ORDER BY $mudanca ASC');

Any suggestions?

I add something that can be useful to someone who is building the same thing:

 <?php 
  $mudanca="data";
 if ($_SERVER["REQUEST_METHOD"] == "POST"){
 $mudanca = $_POST['mudar'];
 }   
 ?>

That is, leave a default variable set, because before the post method was triggered $ change would be empty causing an error in ORDER BY $ change .

    
asked by anonymous 03.09.2014 / 00:03

1 answer

4

Put like this:

$sel = DBRead('artigos', null ,'*', "ORDER BY $mudanca ASC");

That is, double quotation marks!

Within simple quotes PHP does not interpret anything, it puts what is in it as a text only, whereas in double quotation marks if you have PHP variables for example it will interpret and show you the result.

$texto = 'imprime texto';
echo '$texto'; // saída -> $texto
echo "$texto"; // saída -> imprime texto

Example Ideone p>

Or

Concatenation

$sel = DBRead('artigos', null ,'*', 'ORDER BY '.$mudanca.' ASC');

Good reading.

    
03.09.2014 / 00:04