Foros del Web » Programando para Internet » PHP »

Como grabar un dato de un select

Estas en el tema de Como grabar un dato de un select en el foro de PHP en Foros del Web. Hola amigos tengo un problema, estoy queriendo crear un usuario nuevo mediante un formulario y tengo en el mismo que listar mediante un combo desplegable ...
  #1 (permalink)  
Antiguo 27/08/2010, 09:07
 
Fecha de Ingreso: enero-2009
Mensajes: 246
Antigüedad: 15 años, 3 meses
Puntos: 1
Como grabar un dato de un select

Hola amigos tengo un problema, estoy queriendo crear un usuario nuevo mediante un formulario y tengo en el mismo que listar mediante un combo desplegable o select datos de una tabla y grabar los mismos. Esta es mi DB donde tengo los datos para el Select:

Código PHP:
-- 
-- 
Estructura de tabla para la tabla `ubicacion`
-- 

CREATE TABLE `ubicacion` (
  `
idint(20NOT NULL auto_increment,
  `
ubicavarchar(100NOT NULL,
  
PRIMARY KEY  (`id`)
ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=;

-- 
-- 
Volcar la base de datos para la tabla `ubicacion`
-- 

INSERT INTO `ubicacion` (`id`, `ubica`) VALUES 
(1'Clorinda'),
(
2'Pirané'),
(
3'El Colorado'),
(
4'Formosa'),
(
5'Mayorazgo'),
(
6'25 de Mayo'),
(
7'Casbas'); 
Estos datos ya estan grabados y se siguen sumando mas localidades, ahora este es mi php donde cargo los datos para luego grabarlos:

Código PHP:
<form id="loginForm" name="loginForm" method="post" action="register-exec.php">
  <
table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
    <
tr>
      <
th>Nombre </th>
      <
td><input name="fname" type="text" class="textfield" id="fname" /></td>
    </
tr>
    <
tr>
      <
th>Apellido </th>
      <
td><input name="lname" type="text" class="textfield" id="lname" /></td>
    </
tr>
    <
tr>
      <
th width="124">Mail</th>
      <
td width="168"><input name="mail" type="text" class="textfield" id="mail" /></td>
    </
tr>
    <
tr>
      <
th width="124">Ubicacion</th>
      <
td width="168"><select name="ubicacion">
        <
option selected="selected">aca deberia traer los datos de la tabla de arriba</option>
      </
select>
        </
td>
    </
tr>
    <
tr>
      <
th width="124">Login</th>
      <
td width="168"><input name="login" type="text" class="textfield" id="login" /></td>
    </
tr>
    <
tr>
      <
th>Password</th>
      <
td><input name="password" type="password" class="textfield" id="password" /></td>
    </
tr>
    <
tr>
      <
th>Confirmar Password </th>
      <
td><input name="cpassword" type="password" class="textfield" id="cpassword" /></td>
    </
tr>
    <
tr>
      <
td>&nbsp;</td>
      <
td><input type="submit" name="Submit" value="Registrar" /></td>
    </
tr>
  </
table>
</
form
El select con las localidades graba en la DB que marco arriba y el resto de los datos grabaria en la siguiente:

Código PHP:
-- 
-- 
Estructura de tabla para la tabla `members`
-- 

CREATE TABLE `members` (
  `
idint(11unsigned NOT NULL auto_increment,
  `
firstnamevarchar(100) default NULL,
  `
lastnamevarchar(100) default NULL,
  `
mailvarchar(100NOT NULL,
  `
loginvarchar(100NOT NULL default '',
  `
passwdvarchar(32NOT NULL default '',
  `
estadoint(10unsigned NOT NULL default '0',
  `
permisoint(50unsigned NOT NULL default '0',
  `
rolint(3unsigned NOT NULL default '0',
  `
nivelint(3NOT NULL,
ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 
Y por ultimo este seria mi php que graba o realiza el insert en mi DB:

Código PHP:
<?php
    
//Start session
    
session_start();
    
    
//Include database connection details
    
require_once('config.php');
    
    
//Array to store validation errors
    
$errmsg_arr = array();
    
    
//Validation error flag
    
$errflag false;
    
    
//Connect to mysql server
    
$link mysql_connect(DB_HOSTDB_USERDB_PASSWORD);
    if(!
$link) {
        die(
'Failed to connect to server: ' mysql_error());
    }
    
    
//Select database
    
$db mysql_select_db(DB_DATABASE);
    if(!
$db) {
        die(
"Unable to select database");
    }
    
    
//Function to sanitize values received from the form. Prevents SQL injection
    
function clean($str) {
        
$str = @trim($str);
        if(
get_magic_quotes_gpc()) {
            
$str stripslashes($str);
        }
        return 
mysql_real_escape_string($str);
    }
    
    
//Sanitize the POST values
    
$fname clean($_POST['fname']);
    
$lname clean($_POST['lname']);
    
$mail clean($_POST['mail']);
    
$ubicacion clean($_POST['ubicacion']);
    
$login clean($_POST['login']);
    
$password clean($_POST['password']);
    
$cpassword clean($_POST['cpassword']);
    
    
//Input Validations
    
if($fname == '') {
        
$errmsg_arr[] = 'Debe completar el Nombre';
        
$errflag true;
    }
    if(
$lname == '') {
        
$errmsg_arr[] = 'Debe completar el Apellido';
        
$errflag true;
    }
    if(
$mail == '') {
        
$errmsg_arr[] = 'Complete Mail';
        
$errflag true;
    }
    if(
$ubicacion == '') {
        
$errmsg_arr[] = 'Complete Ubicacion';
        
$errflag true;
    }
    if(
$login == '') {
        
$errmsg_arr[] = 'Complete Login';
        
$errflag true;
    }
    if(
$password == '') {
        
$errmsg_arr[] = 'Falta la Password';
        
$errflag true;
    }
    if(
$cpassword == '') {
        
$errmsg_arr[] = 'Falta confirmar Password';
        
$errflag true;
    }
    if( 
strcmp($password$cpassword) != ) {
        
$errmsg_arr[] = 'Las Passwords no coinciden';
        
$errflag true;
    }
    
    
//Check for duplicate login ID
    
if($login != '') {
        
$qry "SELECT * FROM members WHERE login='$login'";
        
$result mysql_query($qry);
        if(
$result) {
            if(
mysql_num_rows($result) > 0) {
                
$errmsg_arr[] = 'Login esta en Uso';
                
$errflag true;
            }
            @
mysql_free_result($result);
        }
        else {
            die(
"Query failed");
        }
    }
    
    
//If there are input validations, redirect back to the registration form
    
if($errflag) {
        
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
        
session_write_close();
        
header("location: registro_usuarios.php");
        exit();
    }

    
//Create INSERT query
    
$qry "INSERT INTO members(firstname, lastname, mail, ubicacion, login, passwd) VALUES('$fname','$lname','$mail','$ubicacion','$login','".md5($_POST['password'])."')";
    
$result = @mysql_query($qry);
    
    
//Check whether the query was successful or not
    
if($result) {
        
header("location: registro_exitoso.php");
        exit();
    }else {
        die(
"Query failed");
    }
?>
La pregunta es la siguiente.

Alguien puede decirme como poder hacer en el primer php para que me liste en el combo las localidades de mi tabla ubicacion y que estas sean grabadas cuando presiono sobre grabar.

Desde ya muy agradecido de antemano a quien pueda corregirme este script o decirme como hacerlo ya que mucha idea no tengo.

Salu2
  #2 (permalink)  
Antiguo 27/08/2010, 09:54
Avatar de dcreate  
Fecha de Ingreso: octubre-2009
Ubicación: Veracruz
Mensajes: 536
Antigüedad: 14 años, 6 meses
Puntos: 22
Respuesta: Como grabar un dato de un select

para mostrar datos de un select:

Código PHP:
<?php include "conexion.php";
conectar();
      
$consulta=mysql_query("SELECT * FROM users");
     
      echo 
"<select name='user'id='user'>";
      echo 
"<option value='0'>Elige..</option>";
      while(
$registro=mysql_fetch_row($consulta))
      {
      echo 
"<option value='".$registro[0]."'>".$registro[1]."</option>";
      }
      echo 
"</select>";
      
      
?>
__________________
Somos lo que pensamos, como pensamos vivimos.

Etiquetas: dato, grabar, select
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:13.