Foros del Web » Programando para Internet » PHP »

Insertar registros array a una base de MySQL

Estas en el tema de Insertar registros array a una base de MySQL en el foro de PHP en Foros del Web. Que tal amigos, un cordial saludo para todos ustedes agradeciendo anticipadamente su ayuda. Estoy creando un sistema de asistencia bastante sencillo, donde tomo la lista ...
  #1 (permalink)  
Antiguo 28/03/2012, 12:39
 
Fecha de Ingreso: marzo-2012
Mensajes: 84
Antigüedad: 12 años, 1 mes
Puntos: 3
Exclamación Insertar registros array a una base de MySQL

Que tal amigos, un cordial saludo para todos ustedes agradeciendo anticipadamente su ayuda. Estoy creando un sistema de asistencia bastante sencillo, donde tomo la lista de estudiantes de una base de datos de en MySQL. En este momento con php hice que en un formulario me aparezcan en textbox todos los alumnos (según vayan ingresando más alumnos se actualice el formulario) y la asistencia con la fecha con textbox vacíos respectivamente para que con un submit me envíe la información a la base de datos de todos los alumnos.

¿Cómo puedo hacer para insertar los datos a una base de MySQL, en diferentes filas?

De antemano gracias por su tiempo y ayuda

Código donde pinto el formulario
Código PHP:
 <?php
   
   $usu_alum
=mysql_query("SELECT ID_ALUMNO FROM ml_dat_ALUMNO WHERE ID_GRUPO = '$nombre_gpo'");
                           
   
   
   echo 
"<table width='765' border='2' align='left'>";
   
   echo 
'<form action="CONEXION_ASISTENCIA.php" id="asist" method="POST">';

echo 
"<tr>";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><font size='-1'><font face='Arial'><b>Alumno</b></td>";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><font size='-1'><font face='Arial'><b>Asistencia</b></td>";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><font size='-1'><font face='Arial'><b>Fecha de asistencia</b></td>";

echo 
"</tr>";

while (
$row_asist mysql_fetch_row($usu_alum)){

echo 
"<tr> \n";

echo 
"<input type='hidden' name='ID_GRUP' id='ID_GRUP' value='$nombre_gpo' />";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><input type='text' name='ALUMNOS' size='20' maxlength='20' value='$row_asist[0]'><font size='-1'><font face='Arial'></td></input> \n";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><input type='text' name='ASIST' size='20' maxlength='20' value=''><font size='-1'><font face='Arial'></td></input> \n";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><input type='text' name='FECHA_ASISTENCIA' size='20' maxlength='20' value=''><font size='-1'><font face='Arial'></td></input> \n";

echo 
"</tr> \n";

}

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><input type='submit' name='ENVIAR' id='ENVIAR' value='Guardar'><input type='reset' name='RESTABLECER' id='RESTABLECER' value='Borrar datos'><font size='-1'><font face='Arial'></td> \n";

echo 
"</font>";

echo 
"</table> \n";
 
echo 
'</form>';
 
 
?>

Código de la consulta
Código PHP:
<?php
$conexion
=mysql_connect("localhost","-----------","-----------");
if (!
$conexion) {
die(
"Fallo la conexión a la Base de Datos: " mysql_error());
}
$db=mysql_select_db("--------------",$conexion);
if (!
$db) {
die(
"Fallo la selección de la Base de Datos: " mysql_error());
}

$GRUPO=$_POST['ID_GRUP'];
$ALUMNO=$_POST['ALUMNOS'];
$ASISTENCIA=$_POST['ASIST'];
$FECHA_ASISTENCIA=$_POST['FECHA_ASISTENCIA'];

$insertar=mysql_query("INSERT INTO ml_dat_ASISTENCIA(ID_GRUPO,ID_ALUMNO,ASISTENCIA,FECHA_ASIST) VALUES('$GRUPO','$ALUMNO','$ASISTENCIA','$FECHA_ASISTENCIA')",$conexion);    
if (!
$insertar) {
die(
"Fallo en la insercion de registro en la Base de Datos: " mysql_error());
}
mysql_close($conexion);

echo 
'<script>alert("Los datos han sido almacenados en la base de datos");</script>';
        echo 
'<SCRIPT LANGUAGE="javascript">
        location.href="MILISTA_BD_ASIST.php";
        </SCRIPT>'
;

?>

EJEMPLO:
No se tiene un número exacto de alumnos, así que pinto en el formulario una tabla con los alumnos que se obtienen de una base de datos de MySQL, sin embargo en la consulta establezco que se envíen los registros de los textbox 'ALUMNO', 'ASISTENCIA' y 'FECHA_ASISTENCIA', por lógica los 23 alumnos se encuentran en el textbox con el mismo nombre y quisiera ingresar los datos de todos ellos, ya que sólo envía el último.

Última edición por chubse; 28/03/2012 a las 14:14
  #2 (permalink)  
Antiguo 28/03/2012, 21:26
Avatar de truman_truman  
Fecha de Ingreso: febrero-2010
Ubicación: /home/user
Mensajes: 1.341
Antigüedad: 14 años, 2 meses
Puntos: 177
Respuesta: Insertar registros array a una base de MySQL

En principio tendrías que llamar a los input TEXT , de la siguiente manera :
Código HTML:
name='ID_GRUP[]'
name='ALUMNOS[]'
name='ASIST[]'
name='FECHA_ASISTENCIA[]'
con esto, al recibir los datos estás recibiendo un array, ejemplo

Código PHP:
registro 1
$_POST
['ID_GRUP'][0]
$_POST['ALUMNOS'][0]
$_POST['ASIST'][0]
$_POST['FECHA_ASISTENCIA'][0]

registro 2
$_POST
['ID_GRUP'][1]
$_POST['ALUMNOS'][1]
$_POST['ASIST'][1]
$_POST['FECHA_ASISTENCIA'][1]

etc etc... 
Con un ciclo for podés recibir el array POST y en cada pasada del for recuperás los datos de cada regostro [$i] ,

Código PHP:
for($i=0$i<sizeoff(POST); $i++){
    
consulta inserta datos


Por ahí va la cosa, para entenderlo mejor ponele los [] a cada name de input text, y en el archivo en donde recibís el formulario poné lo siguiente

Código PHP:
echo '<pre>';
print_r(POST); 
y verás la estructura del array POST
__________________
la la la
  #3 (permalink)  
Antiguo 29/03/2012, 12:26
 
Fecha de Ingreso: marzo-2012
Mensajes: 84
Antigüedad: 12 años, 1 mes
Puntos: 3
Respuesta: Insertar registros array a una base de MySQL

Mi amigo TRUMAN muchas gracias por tu tiempo y ayuda, ya modifiqué mi código como tu me lo has indicado sin embargo me marca un error que dice:

POSTFallo en la insercion de registro en la Base de Datos: Cannot add or update a child row: a foreign key constraint fails (`seresesp_milista/ml_dat_ASISTENCIA`, CONSTRAINT `ID_ALUMNO_R2` FOREIGN KEY (`ID_ALUMNO`) REFERENCES `ml_dat_ALUMNO` (`ID_ALUMNO`) ON DELETE CASCADE ON UPDATE CASCADE)

No se si sea ya cosa de mi base de datos o sea otra cosa:

- La lista de alumnos los tomo del ID_ALUMNOS de una tabla que se llama ml_dat_ALUMNOS.
- Quiero insertar el textbox ID_GRUPO (que toma el ID de una sesión de GRUPO), ALUMNOS (ID tomado de ml_dat_ALUMNOS), ASISTENCIA y FECHA_ASISTENCIA (escrita por el usuario) a otra tabla llamada ml_dat_ASISTENCIA.
- Tengo 2 relaciones:
* ID_GRUPO con la tabla ml_dat_GRUPO.
* ID_ALUMNO con la tabla ml_dat_ALUMNO

Te dejo mi código:

Código formulario
Código PHP:
 <?php

$usuario_gpo
=mysql_query("SELECT ID_GRUPO,GRUPO_NUMERO FROM ml_dat_GRUPO WHERE GRUPO_NUMERO = '$gpo'");
                            
$row_gpo mysql_fetch_row($usuario_gpo);
                            
$nombre_gpo=$row_gpo[0];
   
   
$usu_alum=mysql_query("SELECT ID_ALUMNO FROM ml_dat_ALUMNO WHERE ID_GRUPO = '$nombre_gpo'");
                           
   
   
   echo 
"<table width='765' border='2' align='left'>";
   
   echo 
'<form action="CONEXION_ASISTENCIA.php" id="asist" method="POST">';

echo 
"<tr>";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><font size='-1'><font face='Arial'><b>Alumno</b></td>";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><font size='-1'><font face='Arial'><b>Asistencia</b></td>";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><font size='-1'><font face='Arial'><b>Fecha de asistencia</b></td>";

echo 
"</tr>";

while (
$row_asist mysql_fetch_row($usu_alum)){

echo 
"<tr> \n";

echo 
"<input type='hidden' name='ID_GRUP[]' id='ID_GRUP' value='$nombre_gpo' />";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><input type='text' name='ALUMNOS[]' size='20' maxlength='20' value='$row_asist[0]'><font size='-1'><font face='Arial'></td></input> \n";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><input type='text' name='ASIST[]' size='20' maxlength='20' value=''><font size='-1'><font face='Arial'></td></input> \n";

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><input type='text' name='FECHA_ASISTENCIA[]' size='20' maxlength='20' value=''><font size='-1'><font face='Arial'></td></input> \n";

echo 
"</tr> \n";

}

echo 
"<td width='236' bgcolor='#C4CDFD' align='center'><input type='submit' name='ENVIAR' id='ENVIAR' value='Guardar'><input type='reset' name='RESTABLECER' id='RESTABLECER' value='Borrar datos'><font size='-1'><font face='Arial'></td> \n";

echo 
"</font>";

echo 
"</table> \n";
 
echo 
'</form>';
 
 
?>

Código que recibe del submit
Código PHP:
<?php
$conexion
=mysql_connect("localhost","-------------","--------------");
if (!
$conexion) {
die(
"Fallo la conexión a la Base de Datos: " mysql_error());
}
$db=mysql_select_db("---------------",$conexion);
if (!
$db) {
die(
"Fallo la selección de la Base de Datos: " mysql_error());
}

$GRUPO=$_POST['ID_GRUP[]'];
$ALUMNO=$_POST['ALUMNOS[]'];
$ASISTENCIA=$_POST['ASIST[]'];
$FECHA_ASISTENCIA=$_POST['FECHA_ASISTENCIA[]'];
    
for(
$i=0$i<count(POST); $i++)
{

$insertar=mysql_query("INSERT INTO ml_dat_ASISTENCIA(ID_GRUPO,ID_ALUMNO,ASISTENCIA,FECHA_ASIST) VALUES('$GRUPO[$i]','$ALUMNOS[$i]','$ASISTENCIA[$i]','$FECHA_ASISTENCIA[$i]')",$conexion);    

if (!
$insertar) {
die(
"Fallo en la insercion de registro en la Base de Datos: " mysql_error());
}

mysql_close($conexion);

echo 
'<script>alert("Los datos han sido almacenados en la base de datos");</script>';
        echo 
'<SCRIPT LANGUAGE="javascript">
        location.href="MILISTA_BD_ASIST.php";
        </SCRIPT>'
;
}
?>

NOTA:
- El sizeoff(POST) me marca error así que utilicé count(POST).
- El:
Código PHP:
echo '<pre>'
print_r(POST); 
Tiene la misma función pero lo cambié por:
Código PHP:
if (!$insertar) {
die(
"Fallo en la insercion de registro en la Base de Datos: " mysql_error());
}

mysql_close($conexion);

echo 
'<script>alert("Los datos han sido almacenados en la base de datos");</script>';
        echo 
'<SCRIPT LANGUAGE="javascript">
        location.href="MILISTA_BD_ASIST.php";
        </SCRIPT>'
;


Muchas gracias
  #4 (permalink)  
Antiguo 29/03/2012, 12:49
 
Fecha de Ingreso: marzo-2012
Mensajes: 84
Antigüedad: 12 años, 1 mes
Puntos: 3
Respuesta: Insertar registros array a una base de MySQL

Ya utilicé: sizeof(POST) ------- lo que pasa que me daba error porque lo puse con doble f
pero aún así me marca error
  #5 (permalink)  
Antiguo 29/03/2012, 13:41
 
Fecha de Ingreso: marzo-2012
Mensajes: 84
Antigüedad: 12 años, 1 mes
Puntos: 3
Respuesta: Insertar registros array a una base de MySQL

He modificado un poco el código de donde se envía el formulario y ya se guarda en la tabla ml_dat_ASISTENCIA de la base de datos, pero sólo el primer registro.

Código PHP:
<?php
$conexion
=mysql_connect("localhost","-------------","-------------");
if (!
$conexion) {
die(
"Fallo la conexión a la Base de Datos: " mysql_error());
}
$db=mysql_select_db("----------------",$conexion);
if (!
$db) {
die(
"Fallo la selección de la Base de Datos: " mysql_error());
}

$GRUPO=$_POST['ID_GRUP'];
$ALUMNO=$_POST['ALUMNOS'];
$ASISTENCIA=$_POST['ASIST'];
$FECHA_ASISTENCIA=$_POST['FECHA_ASISTENCIA'];
    
for(
$i=0$i<sizeof(POST); $i++)
{

$insertar=mysql_query("INSERT INTO ml_dat_ASISTENCIA(ID_GRUPO,ID_ALUMNO,ASISTENCIA,FECHA_ASIST) VALUES('$GRUPO[$i]','$ALUMNO[$i]','$ASISTENCIA[$i]','$FECHA_ASISTENCIA[$i]')",$conexion);


if (!
$insertar) {
die(
"Fallo en la insercion de registro en la Base de Datos: " mysql_error());
}

mysql_close($conexion);

echo 
'<script>alert("Los datos han sido almacenados en la base de datos");</script>';
        echo 
'<SCRIPT LANGUAGE="javascript">
        location.href="MILISTA_BD_ASIST.php";
        </SCRIPT>'
;
}

?>
  #6 (permalink)  
Antiguo 29/03/2012, 13:46
Avatar de Nano_  
Fecha de Ingreso: febrero-2006
Ubicación: Bogotá, Colombia
Mensajes: 1.866
Antigüedad: 18 años, 2 meses
Puntos: 96
Respuesta: Insertar registros array a una base de MySQL

Saludos

Te aparece algún error?.. solo hace una iteracion el for? o en cada iteracion siempre te inserta el mismo registro?
__________________
:.:Nano.:: @nano_hard - Retornando al foro
  #7 (permalink)  
Antiguo 29/03/2012, 14:02
 
Fecha de Ingreso: marzo-2012
Mensajes: 84
Antigüedad: 12 años, 1 mes
Puntos: 3
Respuesta: Insertar registros array a una base de MySQL

Ahorita ya no aparece ningún error, pero sólo me inserta el primer registro y los demás no, siempre el mismo.
  #8 (permalink)  
Antiguo 09/04/2012, 18:53
 
Fecha de Ingreso: marzo-2012
Mensajes: 84
Antigüedad: 12 años, 1 mes
Puntos: 3
Respuesta: Insertar registros array a una base de MySQL

Amigos tengo este código y tengo un problema ya que sólo me envía el 1er registro, ¿alguien podría brindarme un poco de apoyo? Se lo agradecería mucho:

Formulario
Código PHP:
<?php
   
   $usu_alum
=mysql_query("SELECT ID_ALUMNO FROM ml_dat_ALUMNO WHERE ID_GRUPO = '$nombre_gpo'");
                   
   
   echo 
'<form action="CONEXION_ASISTENCIA.php" id="asist" method="POST">';

echo 
"<tr>";

echo 
"<b>Alumno</b>";

echo 
"<b>Asistencia</b>";

echo 
"<b>Fecha de asistencia</b>";

echo 
"</tr>";

while (
$row_asist mysql_fetch_array($usu_alum)){

echo 
"<tr> \n";

echo 
"<input type='text' name='ID_GRUP[]' id='ID_GRUP' value='$row_gpo[0]' />";

echo 
"<input type='text' name='ALUMNOS[]' size='20' value='$row_asist[0]'></input> \n";

echo 
"<input type='text' name='ASIST[]' size='20' value=''></input> \n";

echo 
"<input type='text' name='FECHA_ASISTENCIA[]' value=''><font size='-1'></input> \n";

echo 
"</tr> \n";

}

echo 
"<input type='submit' name='ENVIAR' id='ENVIAR' value='Guardar'>
<input type='reset' name='RESTABLECER' id='RESTABLECER' value='Borrar datos'></td> \n"
;

echo 
"</font>";

echo 
"</table> \n";
 
echo 
'</form>';
 
 
?>
Envío de datos
Código PHP:
<?php 
$conexion
=mysql_connect("localhost","---------------","-----------------"); 
if (!
$conexion) { 
die(
"Fallo la conexión a la Base de Datos: " mysql_error()); 

$db=mysql_select_db("---------------------",$conexion); 
if (!
$db) { 
die(
"Fallo la selección de la Base de Datos: " mysql_error()); 


$GRUPO=$_POST['ID_GRUP']; 
$ALUMNO=$_POST['ALUMNOS']; 
$ASISTENCIA=$_POST['ASIST']; 
$FECHA_ASISTENCIA=$_POST['FECHA_ASISTENCIA']; 
     


for(
$i=0$i<sizeof($GRUPO); $i++)  



$insertar=mysql_query("INSERT INTO ml_dat_ASISTENCIA(ID_GRUPO,ID_ALUMNO,ASISTENCIA,FECHA_ASIST) VALUES('$GRUPO[$i]','$ALUMNO[$i]','$ASISTENCIA[$i]','$FECHA_ASISTENCIA[$i]')",$conexion);  

if (!
$insertar) { 
die(
"Fallo en la insercion de registro en la Base de Datos: " mysql_error()); 


mysql_close($conexion); 

echo 
'<script>alert("Los datos han sido almacenados en la base de datos");</script>'
        echo 
'<SCRIPT LANGUAGE="javascript"> 
        location.href="MILISTA_BD_ASIST.php"; 
        </SCRIPT>'



?>

Etiquetas: asistencia, formulario, insert, mysql
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 17:50.