Change the order of a result in PHP WHILE from MySQL [duplicate]

0

I have the following difficulty, in a table are stored product category records, I made the connection mysqli, SELECT and WHILE, and everything is fine until then, but what I'm having is leaving a record of WHILE Finally, in the case it would be the category record called "OTHERS", because the SELECT is with ORDER BY cat_nome ASC; and below "OTHERS" there are other categories with names beginning with "P", "Q", "R", "S" (...).

In short, SELECT looks like this:

<?php
$sql_cat_cad = "SELECT 
                   'cat_id',
                   'cat_nome'
                FROM 
                    'categoria' 
                WHERE 
                    'cat_id_pai' IS NULL
                ORDER BY 
                    'cat_nome'
                        ASC
                ";

$query_cat_cad = mysqli_query( $mysqli, $sql_cat_cad );
$conta_cat_cad = mysqli_num_rows( $query_cat_cad );
if( $conta_cat_cad > 0 ) {
    echo "<select name='categorias' id='categorias'>\n";
    echo "<option value=''>Selecione a categoria</option>\n";
    while( $cat = mysqli_fetch_array( $query_cat_cad ) ) {
        echo "<option value='" . $cat['cat_id'] . "'>" . stripslashes( $cat['cat_nome'] ) . "</option>\n";
    }
    echo "</select>\n";
}
?>

Resulting WHILE:

  

Adapters

     

Forearm Support

     

Speakers and Subwoofer

     

Microphones

     

Mouse Pads

     

Other

     

Scanners

     

CPU Stands

     

USB Padlocks

I would like to change the code to look like this:

  

Adapters

     

Forearm Support

     

Speakers and Subwoofer

     

Microphones

     

Mouse Pads

     

Scanners

     

CPU Stands

     

USB Padlocks

     

Other

    
asked by anonymous 27.08.2018 / 20:02

1 answer

2

First you should get cat_id relative to cat_nome "Others". This way you can do a sort order with a case test:

SELECT cat_id, cat_nome FROM categoria WHERE cat_id_pai IS NULL
ORDER BY (CASE WHEN 'cat_id'=<ID_QUE_ENCONTROU> THEN 1 ELSE 0 END) ASC, cat_nome ASC

Reference: link

EDIT

Dynamically ordering the term:

SELECT 'cat_id', 'cat_nome' FROM 'categoria' WHERE 'cat_id_pai' IS NULL
ORDER BY (CASE WHEN 'cat_nome'="Outros" THEN 1 ELSE 0 END) ASC, 'cat_nome' ASC
    
27.08.2018 / 20:08