Presentando resultados SQL con bucle FOR y WHILE

Bucle

A la hora de presentar en nuestra web un listado (de calificaciones, quizá) lo más frecuente es echar mano de un bucle y entre éstos los más populares son: for y while

Veremos un ejemplo facilón donde podemos elegir qué bucle queremos utilizar para presentar un listado de alumn@s y notas. Todo ocurre en la misma página index.php (como soporte de estilos, vinculamos a index.css).

  • Cuando el visitante llega se encuentra con dos opciones tipo ‘radio’, pincha una de ellas y pulsa el botón “Listar”.
  • La página se recarga y el script PHP se encarga de recoger el valor de la opción ‘radio’
  • El control pasa a un switch y, en función del valor pasado (for o while), se presenta el listado solicitado
  • Tras listar, un enlace nos posibilita volver a comenzar de nuevo
  • Código de index.php


    <?php
    /*
    This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    You cand find a copy of the GNU General Public License in the “license” directory.

    You should have received a copy of the GNU General Public License along with SIESTTA; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.

    Ramon Castro (http://ramoncastro.es)

    Iconos: Proyecto Tango (http://tango.freedesktop.org/Tango_Desktop_Project)

    */

    ?>

    <!– En el encabezado HTML incluimos la referencia a index.css donde manejaremos los
    estilos de la página. Además, cargamos un primer elemento <div> identificado como “Encabezado”
    –>

    <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
    <html xmlns=”http://www.w3.org/1999/xhtml”>
    <head>
    <meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
    <title>Principal</title>
    <link href=”index.css” rel=”stylesheet” type=”text/css” />
    </head>
    <body>
    <div id=”encabezado”>Web de Prueba</div>
    <?php

    /*comprobamos si acabamos de llegar a la página
    o hemos enviado una petición POST*/

    $radio = $_POST['bucle'];

    //si la hemos enviado

    if($radio)

    {

    //conectamos con mysql y con la base de datos

    $con_mysql=mysql_connect(‘localhost’,’scripts’,’scripts’);

    if (!$con_mysql) {echo ‘No se ha podido encontrar el servidor de datos’;exit;}

    mysql_select_db(’scripts’);

    //controlamos con switch

    switch ($radio)

    {

    case ‘for’:

    //hacemos la consulta

    $select = mysql_query(“select * from notas order by alum”);

    //presentamos el elemento <div>
    echo ‘<div id=”contenido”>’;
    echo ‘<img src=”../imgs/not.png” alt=”Notas” />’;
    echo ‘<br />’;
    echo ‘<ul>’;
    echo ‘<br />’;
    echo ‘<li>LISTADO DE NOTAS CON BUCLE FOR</li>’;
    echo ‘<br />’;
    //bucle for
    /*desde el primer resultado de la consulta
    hasta el último extraeremos el nombre de alumn@
    y su nota y lo presentaremos en la lista*/
    for($a=0;$a<(mysql_num_rows($select));$a++)
    {
    $registro = mysql_fetch_array($select);
    $alum = $registro['alum'];
    $nota = $registro['nota'];
    echo ‘<li>’.$alum.’ ‘.$nota.’</li>’;
    }//fin de bucle
    //cerramos lista
    echo ‘</ul>’;

    //salimos de switch
    break;

    case ‘while’:

    //hacemos la consulta

    $select = mysql_query(“select * from notas order by alum”);

    //presentamos el elemento <div>
    echo ‘<div id=”contenido”>’;
    echo ‘<img src=”../imgs/not.png” alt=”Notas” />’;
    echo ‘<br />’;
    echo ‘<ul>’;
    echo ‘<br />’;
    echo ‘<li>LISTADO DE NOTAS CON BUCLE WHILE</li>’;
    echo ‘<br />’;
    //inicializamos la variable contador
    $b=0;
    //montamos el bucle
    /*mientras el contador sea menor que el
    número de registros de la consulta, iremos
    extrayendo el nombre de alumn@ y su nota y
    lo presentaremos en la lista*/
    while($b<mysql_num_rows($select))
    {
    $registro = mysql_fetch_array($select);
    $alum = $registro['alum'];
    $nota = $registro['nota'];
    echo ‘<li>’.$alum.’ ‘.$nota.’</li>’;
    //incrementamos el contador
    $b++;
    }//fin de bucle while
    //cerramos lista
    echo ‘</ul>’;

    //salimos de switch
    break;

    }//fin de switch

    //mostramos enlace para volver atrás
    echo ‘<br />’;
    echo ‘<a href=”index.php”><img src=”../imgs/atras.png” alt=”Volver” title=”Volver” /></a>’;

    //cerramos elemento </div>
    echo ‘</div>’;

    }//fin de if($radio)

    /*si acabamos de llegar a la página
    cargamos el formulario de envío*/

    else

    {

    //mostramos elemento <div>
    echo ‘<div id=”contenido”>’;
    //abrimos formulario para enviar POST
    echo ‘<form method=”post” action=”index.php”>’;
    //mostramos una lista con las opciones ‘radio’
    echo ‘<ul>’;
    echo ‘<li><input type=”radio” name=”bucle” value=”for” />Ver notas con bucle FOR</li>’;
    echo ‘<li><input type=”radio” name=”bucle” value=”while” />Ver notas con bucle WHILE</li>’;
    echo ‘</ul>’;
    echo ‘<br />’;
    //presentamos un botón de envío
    echo ‘<input type=”submit” value=”Listar” name=”b_env” />’;
    //cerramos formulario
    echo ‘</form>’;
    //cerramos elemento <div>
    echo ‘</div>’;

    }//fin de else

    ?>

    Código de index.css


    /*
    This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    You cand find a copy of the GNU General Public License in the “license” directory.

    You should have received a copy of the GNU General Public License along with SIESTTA; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.

    Ramon Castro (http://ramoncastro.es)

    Iconos: Proyecto Tango (http://tango.freedesktop.org/Tango_Desktop_Project)

    */
    *{
    margin:0;

    padding:0;
    }
    ul{list-style:none;}
    li{font-size:11px;}
    a {text-decoration:none;}
    a:link, a:visited{color:#444;}
    a:hover, a:active{color:#0021a5;}
    input{
    border:1px solid #444;
    margin:4px;
    font-size:10px;
    }
    input:hover{
    border:1px solid #0021a5;
    }

    body{

    font-family: Andale Mono;

    font-size:12px;
    }

    div#encabezado{
    text-align:center;
    font-size:44px;
    height:70px;
    border-bottom: 1px solid #444;
    padding:30px;
    background:transparent url(../imgs/encab.png) no-repeat center bottom;
    }

    div#contenido{
    position:absolute;
    top:250px;
    left: 400px;
    width:200px;
    text-align:center;
    }

    Saludos

    [tag]bucle, for, while, php[/tag]


Acerca de esta Entrada