Foros del Web » Creando para Internet » Herramientas y Software »

Como inserto varios registros desde un multiselect

Estas en el tema de Como inserto varios registros desde un multiselect en el foro de Herramientas y Software en Foros del Web. Hola Gente veo que hay muchos que la tiene muy clara. Estoy intentando insertar en una tabla varios registros tomados de un multiselect de una ...
  #1 (permalink)  
Antiguo 26/04/2010, 22:18
 
Fecha de Ingreso: abril-2010
Mensajes: 4
Antigüedad: 14 años
Puntos: 0
Como inserto varios registros desde un multiselect

Hola Gente veo que hay muchos que la tiene muy clara.
Estoy intentando insertar en una tabla varios registros tomados de un multiselect de una Lista/Menu.
El codigo que generé es el siguiente:
Cita:
<?php require_once('Connections/prueba.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO b (Analisis) VALUES (%s)",
GetSQLValueString($_POST['det'], "text"));

mysql_select_db($database_prueba, $prueba);
$Result1 = mysql_query($insertSQL, $prueba) or die(mysql_error());
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO b (id_a) VALUES (%s)",
GetSQLValueString($_POST['textfield'], "int"));

mysql_select_db($database_prueba, $prueba);
$Result1 = mysql_query($insertSQL, $prueba) or die(mysql_error());
}

mysql_select_db($database_prueba, $prueba);
$query_tec = "SELECT Tec FROM tec";
$tec = mysql_query($query_tec, $prueba) or die(mysql_error());
$row_tec = mysql_fetch_assoc($tec);
$totalRows_tec = mysql_num_rows($tec);

mysql_select_db($database_prueba, $prueba);
$query_id = "SELECT a.id FROM a ORDER BY a.id DESC LIMIT 1";
$id = mysql_query($query_id, $prueba) or die(mysql_error());
$row_id = mysql_fetch_assoc($id);
$totalRows_id = mysql_num_rows($id);
?>
<p>&nbsp;</p>
<form name="form1" method="POST" action="<?php echo $editFormAction; ?>">
<p>
<label>
<input name="textfield" type="text" id="textfield" value="<?php echo $row_id['id']; ?>" size="6">
<br>
</label>
<select name="det" size="10" multiple>
<?php
do {
?>
<option value="<?php echo $row_tec['Tec']?>"><?php echo $row_tec['Tec']?></option>
<?php
} while ($row_tec = mysql_fetch_assoc($tec));
$rows = mysql_num_rows($tec);
if($rows > 0) {
mysql_data_seek($tec, 0);
$row_tec = mysql_fetch_assoc($tec);
}
?>
</select>
</p>
<p>
<label>
<input type="submit" name="envio" id="envio" value="Enviar">
</label>
</p>
<input type="hidden" name="MM_insert" value="form1">
</form>
<?php
mysql_free_result($tec);

mysql_free_result($id);
?>
Ahora esto me tira un error el siguiente:

"Cannot add or update a child row: a foreign key constraint fails (`p/b`, CONSTRAINT `b_ibfk_1` FOREIGN KEY (`id_a`) REFERENCES `a` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)"

Le encontré una vuelta no muy profesional que es la siguiente, pero me gustaría la primera:

Cita:
<?php require_once('Connections/prueba.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO b (id_a, Analisis) VALUES (%s, %s)",
GetSQLValueString($_POST['id_a'], "int"),
GetSQLValueString($_POST['Analisis'], "text"));

mysql_select_db($database_prueba, $prueba);
$Result1 = mysql_query($insertSQL, $prueba) or die(mysql_error());

$insertGoTo = "datos.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO b (id_a, Analisis) VALUES (%s, %s)",
GetSQLValueString($_POST['id_a'], "int"),
GetSQLValueString($_POST['select'], "text"));

mysql_select_db($database_prueba, $prueba);
$Result1 = mysql_query($insertSQL, $prueba) or die(mysql_error());
}

mysql_select_db($database_prueba, $prueba);
$query_tec = "SELECT * FROM tec ORDER BY Tec ASC";
$tec = mysql_query($query_tec, $prueba) or die(mysql_error());
$row_tec = mysql_fetch_assoc($tec);
$totalRows_tec = mysql_num_rows($tec);

mysql_select_db($database_prueba, $prueba);
$query_id = "SELECT id FROM a ORDER BY a.id DESC LIMIT 1";
$id = mysql_query($query_id, $prueba) or die(mysql_error());
$row_id = mysql_fetch_assoc($id);
$totalRows_id = mysql_num_rows($id);
?>
<form action="<?php echo $editFormAction; ?>" method="POST" name="form1" id="form1">
<table align="center">
<tr valign="baseline">
<td nowrap="nowrap" align="right">Id_a:</td>
<td><input type="text" name="id_a" value="<?php echo $row_id['id']; ?>" size="32" readonly="readonly"/></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Analisis:</td>
<td><label>
<select name="Analisis" id="Analisis">
<?php
do {
?>
<option value="<?php echo $row_tec['Tec']?>"><?php echo $row_tec['Tec']?></option>
<?php
} while ($row_tec = mysql_fetch_assoc($tec));
$rows = mysql_num_rows($tec);
if($rows > 0) {
mysql_data_seek($tec, 0);
$row_tec = mysql_fetch_assoc($tec);
}
?>
</select>
</label></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Analisis</td>
<td><label>
<select name="select" id="select">
<?php
do {
?>
<option value="<?php echo $row_tec['Tec']?>"><?php echo $row_tec['Tec']?></option>
<?php
} while ($row_tec = mysql_fetch_assoc($tec));
$rows = mysql_num_rows($tec);
if($rows > 0) {
mysql_data_seek($tec, 0);
$row_tec = mysql_fetch_assoc($tec);
}
?>
</select>
</label></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">&nbsp;</td>
<td><input type="submit" value="Insertar registro" /></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form1" />
</form>
<p>&nbsp;</p>

<?php
mysql_free_result($tec);

mysql_free_result($id);
?>
Esta si anda.
Como podría hacer lo mismo pero con la primera? A alguien se le ocurre algo?
Desde ya muchas gracias, excelente foro!!
Diego
  #2 (permalink)  
Antiguo 27/04/2010, 15:54
Avatar de juaniquillo
Colaborador
 
Fecha de Ingreso: noviembre-2005
Ubicación: San Juan, Puerto Rico
Mensajes: 5.745
Antigüedad: 18 años, 5 meses
Puntos: 281
Respuesta: Como inserto varios registros desde un multiselect

a ver si entiendo con el código. ¿quieres tener un menú donde puedes escoger múltiples opciones e insertar esas opciones en la base de datos? si es así puedes enviar las opciones como un array y hacer múltiples entradas dependiendo de los elementos que tenga el array. aquí le explico a un usuario como hacerlo:


http://www.forosdelweb.com/f17/inser...region-795227/
__________________
Por fin.. tengo algo parecido a un blog
Y por lo visto ya estoy escribiendo...
  #3 (permalink)  
Antiguo 29/04/2010, 07:30
 
Fecha de Ingreso: abril-2010
Mensajes: 4
Antigüedad: 14 años
Puntos: 0
Respuesta: Como inserto varios registros desde un multiselect

Hola juaniquillo, muchas gracias por responder. Agrege el codigo como sugeriste pero agrega solo un registro de los que selecciono. El codigo es:
Cita:
<?php require_once('Connections/prueba.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
foreach($_POST["Analisis"] as $key => $value){
$insertSQL = sprintf("INSERT INTO b (id_a, Analisis) VALUES (%s, %s)",
GetSQLValueString($_POST['id_a'][$key], "int"),
GetSQLValueString($_POST['Analisis'][$key], "text"));

mysql_select_db($database_prueba, $prueba);
$Result1 = mysql_query($insertSQL, $prueba) or die(mysql_error());

$insertGoTo = "datos.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
}
mysql_select_db($database_prueba, $prueba);
$query_id = "SELECT id FROM a ORDER BY a.id DESC LIMIT 1";
$id = mysql_query($query_id, $prueba) or die(mysql_error());
$row_id = mysql_fetch_assoc($id);
$totalRows_id = mysql_num_rows($id);

mysql_select_db($database_prueba, $prueba);
$query_tec = "SELECT tec.Tec FROM tec";
$tec = mysql_query($query_tec, $prueba) or die(mysql_error());
$row_tec = mysql_fetch_assoc($tec);
$totalRows_tec = mysql_num_rows($tec);
?>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sin t&iacute;tulo</title>
</head>

<body>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
<table align="center">
<tr valign="baseline">
<td nowrap align="right">Id_a:</td>
<td><input type="text" name="id_a" value="<?php echo $row_id['id']; ?>" size="32"></td>
</tr>
<tr valign="baseline">
<td align="right" valign="top" nowrap>Analisis:</td>
<td><label>
<select name="Analisis[]" size="10" multiple id="Analisis">
<?php
do {
?>
<option value="<?php echo $row_tec['Tec']?>"><?php echo $row_tec['Tec']?></option>
<?php
} while ($row_tec = mysql_fetch_assoc($tec));
$rows = mysql_num_rows($tec);
if($rows > 0) {
mysql_data_seek($tec, 0);
$row_tec = mysql_fetch_assoc($tec);
}
?>
</select>
</label></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">&nbsp;</td>
<td><input type="submit" value="Insertar registro"></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form1">
</form>
<p>&nbsp;</p>
</body>
</html><?php
mysql_free_result($id);

mysql_free_result($tec);
?>
Si podes verlo seria bueno, para encontrarle la vuelta a este problema.
Desde ya muchas gracias.
Diego
  #4 (permalink)  
Antiguo 30/04/2010, 08:23
Avatar de juaniquillo
Colaborador
 
Fecha de Ingreso: noviembre-2005
Ubicación: San Juan, Puerto Rico
Mensajes: 5.745
Antigüedad: 18 años, 5 meses
Puntos: 281
Respuesta: Como inserto varios registros desde un multiselect

Pues qué raro, yo lo veo todo bien. Verifica que estás enviando un array haciendo un print_r. Puedes ponerlo antes de la función arriba, así:

Código PHP:
Ver original
  1. <?php require_once('Connections/prueba.php'); ?>
  2. <?php
  3.  
  4. //aquí
  5. echo '<pre>';
  6. print_r($_POST['select']);
  7. echo '</pre>';
  8.  
  9. if (!function_exists("GetSQLValueString")){

Es esta forma verás si estás enviando múltiples opciones o no.
__________________
Por fin.. tengo algo parecido a un blog
Y por lo visto ya estoy escribiendo...
  #5 (permalink)  
Antiguo 30/04/2010, 14:28
 
Fecha de Ingreso: abril-2010
Mensajes: 4
Antigüedad: 14 años
Puntos: 0
Respuesta: Como inserto varios registros desde un multiselect

Hola Juaniquillo, encontré el "error", le quité el $key a la entrada del id_a y lo hizo!
Asi que muchísimas gracias,
Un abrazo desde Argentina
  #6 (permalink)  
Antiguo 30/04/2010, 16:15
Avatar de juaniquillo
Colaborador
 
Fecha de Ingreso: noviembre-2005
Ubicación: San Juan, Puerto Rico
Mensajes: 5.745
Antigüedad: 18 años, 5 meses
Puntos: 281
Respuesta: Como inserto varios registros desde un multiselect

Pues que bueno que te funcionó. Saludos y suerte.
__________________
Por fin.. tengo algo parecido a un blog
Y por lo visto ya estoy escribiendo...

Etiquetas: editores-web, registros
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 02:15.