How to order ID's from highest to lowest

0

I need to show the data of the last one that was uploaded to the last one by means of the id. but the query I have shows me from first to last.

function obtener_post_por_id($conexion, $id){
    $resultado = $conexion->query("SELECT * FROM articulos WHERE id = $id LIMIT 1");
    $resultado = $resultado->fetchAll();
    return ($resultado) ? $resultado : false;
}
    
asked by Yair_May 11.06.2018 в 17:49
source

2 answers

0

You must use ORDER BY that allows you to sort the records thrown out of your query. In specific how you need the last record entered it is convenient to use ORDER BY id DESC which means order according to the field id from highest to lowest, that is, you would select from the last record entered (because you already have LIMIT 1 indicating that you bring only one registration as a result)

Then your sql statement would be:

$resultado = $conexion->query("SELECT * FROM articulos WHERE id = $id LIMIT 1");

and your code with the improvement would be as follows:

function obtener_post_por_id($conexion, $id){
    $resultado = $conexion->query("SELECT * FROM articulos WHERE id = $id ORDER BY id DESC LIMIT 1");
    $resultado = $resultado->fetchAll();
    return ($resultado) ? $resultado : false;
}

Observation: It is not advisable to pass the data directly to your query without having previously "escaped" them correctly to avoid security flaws in your application. You can read more about what I mention here: which is the SQL injection and steps to avoid SQL injection

    
answered by 11.06.2018 / 17:52
source
0

To sort within a QUERY MYSQL, you can use the ORDER BY to specify the column you want to sort the records and then put an ASC or DESC at the end to bring them UP or DOWN as needed.

"SELECT * FROM articulos WHERE id = $id LIMIT 1 ORDER BY id DESC"

It would be more or less what you would need to get the data the way you need to

* EDITION, as you well mention @ the-breaker must be DESC, I got confused with the first sentence of the question.

    
answered by 11.06.2018 в 17:53