Formulario select con opciones desde tabla mysql

Creo que podemos decir que esta Auto-Documentado :)
Ya lo vi funcionando bien con
- Xampp configuración por defecto
- Sobre Debian
- Y navegador Iceweacel (ocease Firefox®)

Cualquier sugerencia es bienvenida...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type">
  <title>Mi ejemplo de select form db data filled</title>
  <meta content="enrique otero" name="author">
  <meta name="copyright" content="GNU_GPL">
</head>
<body>
<!--El código de la función lo tome de Miguel Angel Alvarez en
w3.desarrolloweb.com/articulos/1608.php
DesarrolloWeb es un buen sitio, no puedo negar lo mucho que me ha ayudado,
lo digo como gesto de agradecimiento y sin animo de promocionar a nadie...
!GRACIAS¡-->
<!--
Este escript sirve para llenar los campos "<option value></option>" y
"<option selected value></option>"
que son los posibles valores que el usuario puede seleccionar de un
de un formulario html del tipo "select" que es un "menú desplegable"
En este ejemplo tenemos dos bloques de código PHP:
-El primero de ellos define la función "saca_menu_desplegable"
-El segundo realiza la conexión con el servidor de BD, selecciona BD,
 establece el valor de la variable $ssql y ejecuta la función.
-->
<!--Debemos suponer que:
-Tenemos una base de datos llamada "obras"
-Tenemos una tabla llamada "CATALOG_ARTISTAS"
-Tenemos las columnas "ID, NOMBRE, APELL_PAT, APELL_MAT" dentro de nuestra tabla
-->
<?php
/*Definimos la función que buscará los registros en la base de datos.
Va a tener tres parametros:
1-$ssql----Que será el query para buscar los registros en la BD
2-$valor---Que sera el valor por defecto que tomará el
           formulario (en este caso 4 que corresponde a "pablo")
3-$nombre--Que será el nombre del formulario*/
function saca_menu_desplegable($ssql,$valor,$nombre){
/*con echo damos la instrucción para que se escriba la etiqueta
"<select name=''>" que construye el formulario de lista "select"
y le pasamos el valor de la variable $nombre, no debemos olvidar
cerrar la etiqueta con otro echo al final "</select>"*/
   echo "<select name=\'$nombre\'>";
/*creamos la variable $resultado, que va a almacenar los resultados
del query, la función mysql_query obtiene como parametro la variable
ssql, que a su vez es parametro de la función saca_menu_desplegable*/
   $resultado=mysql_query($ssql);
/*sobre la variable resultado ejecutamos la funcion mysql_fetch_row que
devuelve la suguiente fila o null cuanod se acaban las filas (o la primera
fila, si existe, cuando comienza a ejecutarse) de los datos almacenados en
$result. Almacenamos cada fila obtenida en la variable $fila.
Finalmente, con la sentencia while, repetimos la operación mientras que
mysql_fetch_row nos devuelva una fila, el proceso se detiene cuando
fetch_row devuelve null, es decir, cuando se acaban las filas*/
   while ($fila=mysql_fetch_row($resultado)){
/*intecalado con el proceso anterior, por cada fila que fetch row devuelve,
la sentencia "if" comprueba si la fila es la que se selecciono como valor
por defecto, si cumple con el criterio entonces escribe la fila como la opción
por defecto del formulario, de lo contrario la escribe como opción normal.
Para terminar todo bien y poder ver los nombres en lugar de los ID's de cada
fila debemos tener cuidado al momento de escribirlos de foma tal que queden:
"echo "<option value='ID'>FNAME</option>" para los valores normales o ...
"echo "<option selected value='ID'>FNAME</option>" para el valor por defecto
Debemos pues saber que el método para acceder a las columnas de las filas
recuperadas por mysql_fetch_row y almacenadas dentro de una variable es:
$variable[No de columna]
En nuestro ejemplo esto es:
$fila[0]--> Será igual a la primera columna del registro, ocea ID
$fila[1]--> Será igual a la segunda columna del registro, ocea FNAME*/
     if ($fila[0]==$valor){
       echo "<option selected value='$fila[0]'>$fila[1]</option>";
     }
     else{
       echo "<option value='$fila[0]'>$fila[1]</option>";
     }
  }
   echo "</select>";
}
?>

<?php
/*Aquí comienza nuestro segundo bloque, lo primero que hacemos es
establecer la conexión con la BD*/
$conexion=mysql_connect("localhost","root")
or die("Problemas en la conexion");
/*Seleccionamos la base de datos "obras"*/
mysql_select_db("obras",$conexion) or
die("Problemas en la seleccion de la base de datos");
/*Establecemos los valores de la variable $ssql que es la sentencia
sql que hará la búsqueda dentro de nuestra BD y nuestra tabla
En este caso le digo que seleccione el campo "ID" y posteriormente
le digo que también seleccione la concatenación de las cadenas de los
campos NOMBRE, APELL_PAT y APELL_MAT agregando especios en blanco
entre cada cadena. A esta concatenación la llamaremos "FNAME", de
"Full Name" o "nombre completo"; finalmente le pido que me ordene los
registros por FNAME, para tenerlos por orden alfabetico y no por su ID)*/
$ssql="SELECT ID, CONCAT( NOMBRE, ' ', APELL_PAT, ' ', APELL_MAT ) AS FNAME FROM CATALOG_ARTISTAS order by FNAME";
/*$ssql="select ID,NOMBRE from CATALOG_ARTISTAS";*/
/*Terminamos nuestro script con la llamada a la función
"saca_menu_desplegable", y le damos como parámetros:
-$ssql, la variable que contiene la sentencia sql para obtener los registros
-4, que corresponde al ID del registro que queremos tener por defecto en nuestro formulario
-'FNAMES', que es el nombre del formulario*/
saca_menu_desplegable($ssql,4,'FNAMES');
?>
<br>
<br>
<br>
<!--Finalmente pongo lo mismo pero sin tanto choro para poder copypastear el script-->
<?php
/*definición de la función*/
function saca_menu_desplegable2($ssql,$valor,$nombre){
   echo "<select name=\'$nombre\'>";
   $resultado=mysql_query($ssql);
   while ($fila=mysql_fetch_row($resultado)){
     if ($fila[0]==$valor){
       echo "<option selected value='$fila[0]'>$fila[1]</option>";
     }
     else{
       echo "<option value='$fila[0]'>$fila[1]</option>";
     }
  }
   echo "</select>";
}
?>
<?php
/*ejecución de la función*/
$conexion=mysql_connect('localhost', 'mysql_user', 'mysql_password');
or die("Problemas en la conexion");
mysql_select_db("obras",$conexion) or
die("Problemas en la seleccion de la base de datos");
$ssql="SELECT ID, CONCAT( NOMBRE, ' ', APELL_PAT, ' ', APELL_MAT ) AS FNAME FROM CATALOG_ARTISTAS order by FNAME";
saca_menu_desplegable2($ssql,1,'FNAMES');
?>
</body>
</html>
 

16 Comments

  1. chocochuck5
    Posted 19 julio 2010 at 10:09 PM | Permalink | Responder

    Yo sé que no es el lugar ni el momento, pero te mandé la cotización para unas playeras, por favor responde rápido, me urgen.

    En otros asuntos… que desolado tienes el blog ultimamente, mi feed rss se sorprende cada que ve una actualización tuya jaja, cuídate hermano.

    Saludos.

  2. Posted 10 diciembre 2012 at 6:22 AM | Permalink | Responder

    WOW just what I was searching for. Came here by searching for 2-2-1 full
    court press

  3. Posted 22 marzo 2013 at 9:28 AM | Permalink | Responder

    And didn’t additionally they tell you they purchased it on the web from their residence and had it delivered totally free. This is the pace to start out gradually stirring prior to making as much as the many others.

  4. Posted 19 abril 2013 at 5:12 PM | Permalink | Responder

    Hi, I do believe this is a great web site. I stumbledupon it 😉 I’m going to return once again since I bookmarked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.

  5. Posted 25 abril 2013 at 6:31 AM | Permalink | Responder

    Howdy would you mind sharing which blog platform you’re using? I’m going to start my own blog in the near future but
    I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something unique.
    P.S Apologies for getting off-topic but I had
    to ask!

  6. Posted 9 May 2013 at 7:47 PM | Permalink | Responder

    Attachment parenting will be the practice
    of allowing babies to formulate attachments to individuals and relationships instead of inanimate objects.
    ‘ Monitor any ongoing medical ailments, and try to prevent infections.

  7. Posted 20 May 2013 at 1:00 AM | Permalink | Responder

    The truth of going to be the matter is the fact that typically that
    back pain can be the situation dodged leaving gonna be the
    right sitting and standing postures. Alternatively, foot orthotics are arch supports that are custom-made for every single individual.

  8. Posted 10 junio 2013 at 8:14 AM | Permalink | Responder

    Genetic testing by maternal serum analysis or amniocentesis can confirm diagnosis.
    Apparently, this bacterium might be passed by human exposure, from mother to child
    for example.

  9. Posted 19 junio 2013 at 3:41 PM | Permalink | Responder

    I want to to thank you for this very good read!! I definitely
    loved every bit of it. I have got you book-marked
    to look at new things you post…

  10. Posted 6 agosto 2013 at 2:56 PM | Permalink | Responder

    I am genuinely grateful to the holder of this web page who has shared this impressive paragraph at here.

  11. conrado
    Posted 10 noviembre 2013 at 7:20 AM | Permalink | Responder

    Gracias, muy buen aporte….ahora me trae un problema…..cuando quiero levantar con ajax para captar las variables sin refrescar pagina…no me muestra nada. Se entendió?

  12. Posted 13 octubre 2014 at 8:56 PM | Permalink | Responder

    Un buen blog, muy comodo de leer y de entender.

    Yo tengo con un proyecto mas sencillo

  13. Posted 2 agosto 2015 at 4:16 AM | Permalink | Responder

    certainly like your web-site but you need to check the spelling on quite a few of your posts.
    Several of them are rife with spelling problems and I find it very troublesome to tell the reality then again I’ll surely come again again.

  14. Posted 23 noviembre 2015 at 8:45 PM | Permalink | Responder

    I do not even know the way I stopped up right here, but I believed this submit was once good.
    I do not realize who you are but certainly you’re going to a famous blogger if you happen to are
    not already. Cheers!

  15. Posted 11 diciembre 2015 at 6:17 PM | Permalink | Responder

    What’s Taking place i am new to this, I stumbled
    upon this I have discovered It absolutely useful and it has aided me out
    loads. I hope to give a contribution & aid other customers like its aided me.

    Good job.

10 Trackbacks

  1. By fifa 15 android not connecting to server on 7 abril 2015 at 7:05 AM

    fifa 15 android not connecting to server

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  2. By fifa 15 vs fifa 14 on 20 May 2015 at 10:19 PM

    fifa 15 vs fifa 14

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  3. By shooting games online on 29 agosto 2015 at 6:33 PM

    shooting games online

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  4. By better golf on 31 agosto 2015 at 4:20 AM

    better golf

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  5. By hair extension stylist on 2 septiembre 2015 at 5:26 PM

    hair extension stylist

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  6. By professional sales on 3 septiembre 2015 at 10:04 AM

    professional sales

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  7. By asian handicap ejido on 4 septiembre 2015 at 1:39 AM

    asian handicap ejido

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  8. By sales arena on 4 septiembre 2015 at 4:40 AM

    sales arena

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  9. By game supply on 5 septiembre 2015 at 3:48 AM

    game supply

    Formulario select con opciones desde tabla mysql « Re-Vapaus

  10. By hair thinning on 5 septiembre 2015 at 6:05 PM

    hair thinning

    Formulario select con opciones desde tabla mysql « Re-Vapaus

Escribe un comentario

Required fields are marked *

*
*