Foros del Web » Programando para Internet » PHP »

Como ordenar una variable de mayor a menor?

Estas en el tema de Como ordenar una variable de mayor a menor? en el foro de PHP en Foros del Web. Hola, que tal?, estoy intentando que la lista se ordene de mayor a menor (pago), y en caso que se repita el numero de la ...
  #1 (permalink)  
Antiguo 04/01/2016, 08:18
 
Fecha de Ingreso: noviembre-2012
Mensajes: 13
Antigüedad: 11 años, 5 meses
Puntos: 0
Como ordenar una variable de mayor a menor?

Hola, que tal?, estoy intentando que la lista se ordene de mayor a menor (pago), y en caso que se repita el numero de la variable, se ordene por la id menor.
Me gustaría que alguien me pueda dar una mano.
Aqui les dejo el codigo.


Código PHP:
<?php

/*
* The MIT License
*
* Copyright 2015 nahuel.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

include_once './config.php';


$tipo filter_input(INPUT_GET"id");

if (
preg_match("/[0-9]/"$tipo) && strlen($tipo) <= 2) {

$sql_minimo "SELECT min(`id`) FROM `" $prefix "faucet` WHERE `status` = '1';";
$min $mysqli->query($sql_minimo);
$dataMin $min->fetch_assoc()['min(`id`)'];

if (
$tipo $dataMin) {
$tipo $dataMin;
}

$sql_cantidad_faucetbox "SELECT * FROM `" $prefix "faucet` WHERE `id` = '" $tipo "' AND `status` = '1';";
$config $mysqli->query($sql_cantidad_faucetbox);
$data $config->fetch_assoc();

$sql_ant "SELECT max(`id`) FROM `" $prefix "faucet` WHERE `id` < " $tipo " AND `status` = 1;";
$sql_sig "SELECT min(`id`) FROM `" $prefix "faucet` WHERE `id` > " $tipo " AND `status` = 1;";

$idSig $mysqli->query($sql_sig)->fetch_assoc()['min(`id`)'];

$idAnt $mysqli->query($sql_ant)->fetch_assoc()['max(`id`)'];
if (
$idAnt == NULL) {
$idAnt $dataMin;
}


$layout = new Template("../style/template/sitios/carga.tpl");

switch (
$data['tipo']) {
case 
2: {
$s_pago "Xapo";
}
case 
3: {
$s_pago "ePay";
}
default : {
$s_pago "Faucetbox";
}
}

$layout->set("site_title"$data['nombre']);
$layout->set("ubic"$data['ubic']);

$layout->set("color"$data['color']);
$layout->set("referer"$data['url_r']);


if (
$data['ad1'] == $data['ad2'] && $data['ad2'] == $data['ad3'] && $data['ad3'] == "") {
$layout->set("ancho"0);
} else {
$layout->set("ancho"$data['ancho']);
}



$layout->set("url"$data['url'] . $data['url_r']);

$layout->set("title"$title);
$layout->set("pago"$data['pago']);
$layout->set("tiempo"$data['tiempo']);

$layout->set("s_pago"$s_pago);
$layout->set("total_faucetbox"0);
$layout->set("ant_faucet""../include/cargaFaucet.php?id=" $idAnt);

$layout->set("home""../");
$layout->set("next""../include/cargaFaucet.php?id=" $idSig);
$layout->set("address"$cartera);

$layout->set("ad1"html_entity_decode($data['ad1']));
$layout->set("ad2"html_entity_decode($data['ad2']));
$layout->set("ad3"html_entity_decode($data['ad3']));

echo 
$layout->output();
}
  #2 (permalink)  
Antiguo 04/01/2016, 09:19
 
Fecha de Ingreso: octubre-2010
Ubicación: España
Mensajes: 1.007
Antigüedad: 13 años, 6 meses
Puntos: 123
Respuesta: Como ordenar una variable de mayor a menor?

Utiliza order by
  #3 (permalink)  
Antiguo 04/01/2016, 09:44
 
Fecha de Ingreso: noviembre-2012
Mensajes: 13
Antigüedad: 11 años, 5 meses
Puntos: 0
Respuesta: Como ordenar una variable de mayor a menor?

Puse

Código PHP:
SELECT idnamepago 
FROM tabla
ORDER BY 3 DESC

Y no me carga la pagina
  #4 (permalink)  
Antiguo 04/01/2016, 10:00
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 5 meses
Puntos: 2658
Respuesta: Como ordenar una variable de mayor a menor?

Si la pagina no carga, no es problema de la consulta. Hay un error en otra parte.

Postea el codigo tal y como lo escribiste cuando usaste ese ORDER BY.
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)
  #5 (permalink)  
Antiguo 04/01/2016, 10:30
 
Fecha de Ingreso: noviembre-2012
Mensajes: 13
Antigüedad: 11 años, 5 meses
Puntos: 0
Respuesta: Como ordenar una variable de mayor a menor?

Código PHP:
<?php

/*
 * The MIT License
 *
 * Copyright 2015 nahuel.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

include_once './config.php';


$tipo filter_input(INPUT_GET"id");


if (
preg_match("/[0-9]/"$tipo) && strlen($tipo) <= 2) {

SELECT idnamepago 
FROM tabla 
ORDER BY 3 DESC
;

    
$sql_minimo "SELECT min(`id`) FROM `" $prefix "faucet` WHERE `status` = '1';";
    
$min $mysqli->query($sql_minimo);
    
$dataMin $min->fetch_assoc()['min(`id`)'];

    if (
$tipo $dataMin) {
        
$tipo $dataMin;
    }

    
$sql_cantidad_faucetbox "SELECT * FROM `" $prefix "faucet` WHERE `id` = '" $tipo "' AND `status` = '1';";
    
$config $mysqli->query($sql_cantidad_faucetbox);
    
$data $config->fetch_assoc();

    
$sql_ant "SELECT max(`id`) FROM `" $prefix "faucet` WHERE `id` < " $tipo " AND `status` = 1;";
    
$sql_sig "SELECT min(`id`) FROM `" $prefix "faucet` WHERE `id` > " $tipo " AND `status` = 1;";

    
$idSig $mysqli->query($sql_sig)->fetch_assoc()['min(`id`)'];

    
$idAnt $mysqli->query($sql_ant)->fetch_assoc()['max(`id`)'];
    if (
$idAnt == NULL) {
        
$idAnt $dataMin;
    }


    
$layout = new Template("../style/template/sitios/carga.tpl");

    switch (
$data['tipo']) {
        case 
2: {
                
$s_pago "Xapo";
            }
        case 
3: {
                
$s_pago "ePay";
            }
        default : {
                
$s_pago "Faucetbox";
            }
    }

    
$layout->set("site_title"$data['nombre']);
    
$layout->set("ubic"$data['ubic']);

    
$layout->set("color"$data['color']);
    
$layout->set("referer"$data['url_r']);


    if (
$data['ad1'] == $data['ad2'] && $data['ad2'] == $data['ad3'] && $data['ad3'] == "") {
        
$layout->set("ancho"0);
    } else {
        
$layout->set("ancho"$data['ancho']);
    }



    
$layout->set("url"$data['url'] . $data['url_r']);

    
$layout->set("title"$title);
    
$layout->set("pago"$data['pago']);
    
$layout->set("tiempo"$data['tiempo']);

    
$layout->set("s_pago"$s_pago);
    
$layout->set("total_faucetbox"0);
    
$layout->set("ant_faucet""../include/cargaFaucet.php?id=" $idAnt);

    
$layout->set("home""../");
    
$layout->set("next""../include/cargaFaucet.php?id=" $idSig);
    
$layout->set("address"$cartera);

    
$layout->set("ad1"html_entity_decode($data['ad1']));
    
$layout->set("ad2"html_entity_decode($data['ad2']));
    
$layout->set("ad3"html_entity_decode($data['ad3']));

    echo 
$layout->output();
}
  #6 (permalink)  
Antiguo 04/01/2016, 10:55
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 5 meses
Puntos: 2658
Respuesta: Como ordenar una variable de mayor a menor?

Código PHP:
Ver original
  1. if (preg_match("/[0-9]/", $tipo) && strlen($tipo) <= 2) {
  2.  
  3. SELECT id, name, pago  
  4. FROM tabla  
  5. ORDER BY 3 DESC;
  6.  
  7.     $sql_minimo = "SELECT min(`id`) FROM `" . $prefix . "faucet` WHERE `status` = '1';";

¿Sabes que PHP no interpreta ni entiende SQL, no?

No puedes poner SQL en un código PHP, ni tampoco PHP en un script SQL. SOn lenguajes y entornos de existencia total y absolutamente independientes, que sólo interactúan por medio de librerías de conexión.
Si quieres ejecutar una sentencia SQL, la debes cargar en una variable de cadena, y enviarla a ejecutar a MySQL por medio de una función específica de la librería de que usas. De lo contrario...

Así como lo pones, se interrumpe la ejecución de PHP porque encuentra algo que simplemente no hace nada, y no puede parsear.
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)
  #7 (permalink)  
Antiguo 04/01/2016, 11:04
 
Fecha de Ingreso: noviembre-2012
Mensajes: 13
Antigüedad: 11 años, 5 meses
Puntos: 0
Respuesta: Como ordenar una variable de mayor a menor?

Disculpa la ignorancia, soy nuevo en PhP, se muy muy lo básico... como haría para que pueda ordenar de mayor a menor segun la columna pago?
  #8 (permalink)  
Antiguo 04/01/2016, 11:14
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 5 meses
Puntos: 2658
Respuesta: Como ordenar una variable de mayor a menor?

Eso ya te lo expliqué en el foro de MySQL.

Código MySQL:
Ver original
  1. SELECT ID, nombre, pago
  2. FROM pagos
  3. GROUP BY ID ASC, pago DESC

Lo que debes hacer ahora es integrar esa consulta que te propuse (previamente probarla), a la llamada donde la vas a usar.
Sin ver todo el código, es posible que debas reescribir bastantes partes para hacer algo que te funcione bien, porque en todo tu código no veo ninguna parte donde estés consultando por los pagos de nada. Sólo veo llamadas para buscar el máximo ID en diferentes partes.
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)

Etiquetas: html, mayor, mysql, select, sql, variable
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 21:55.