Comunidad de diseño web y desarrollo en internet online

Insertar mas de un registro a la vez

Citar            
MensajeEscrito el 22 Ago 2008 09:31 pm
Estoy haciendo un formulario que se genera sus filas deacuerdo a una variable pasada desde una pagina anterior y quiero que cada linea sea un nuevo registro talvez no me explico bien aqui el codigo

Código :

<?php require_once('Connections/Rest.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"] == "new_form")) {
# En este punto establezco la variable $i que me ayudara a contar el numero de veces que se debe ejecutar el do ... while
$i = 0;
do { 
   $i++;
     $insertSQL = sprintf("INSERT INTO menu (plato, prec) VALUES (%s, %s)",
                            GetSQLValueString($_POST['platillo'.$i], "text"),
                      GetSQLValueString($_POST['precio'.$i], "text"));

     mysql_select_db($database_Rest, $Rest);
     $Result1 = mysql_query($insertSQL, $Rest) or die(mysql_error());
} while ($i+1 <= $_SESSION['cant']);

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

session_start();
include ('header.php');
?>
<form action="<?php echo $editFormAction; ?>" name="new_form" id="new_form" method="POST" enctype="multipart/form-data">
<table width="95%" border="0" cellspacing="5" cellpadding="0" align="center">
  <tr>
    <td colspan="3" align="center">Menu
      del D&iacute;a</td>
  </tr>
  <tr>
    <td width="5%" align="center">ID</td>
    <td width="75%">Platillo</td>
    <td width="20%" align="center">Costo</td>
  </tr>
  <?
   $o = 0;
   do { $o++;  ?>
  <tr>
    <td align="center"><input name='<? echo "Id".$o;?>' type="text" id='<? echo "Id".$o;?>' style="width:25px; text-align:center" maxlength="2" value='<? echo $o; ?>' readonly>    </td>
    <td align="left"><input type="text" name='<? echo "platillo".$o;?>' id='<? echo "platillo".$o;?>' style="width:100%">    </td>
    <td align="center"> S/.
      <input name='<? echo "precio".$o;?>' type="text" id='<? echo "precio".$o;?>' maxlength="5" style="width:50px; text-align:right">    </td>
  </tr>
  <? } while ($o <= $_SESSION[cant]); ?>
  
  <tr>
    <td colspan="3" align="right"><input name="Actualizar" type="submit" value="Actualizar Menu">    </td>
  </tr>
</table>
<input type="hidden" name="MM_insert" value="new_form">
</form>


Cuando ejecuto la página el script para insertar registro solo se ejecuta solo una unica vez.

Aqui el codigo de la pagina que dirige a esta

Código :

<?php require_once('Connections/Rest.php'); ?>
<?php
session_start();
include ('header.php');
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_Accion"])) && ($_POST["MM_Accion"] == "nuevo")) {
$query = sprintf("TRUNCATE TABLE menu");
mysql_select_db($database_Rest, $Rest);
$sentencia = mysql_query($query, $Rest) or die(mysql_error());
# La variable de session pasara para generar el numero de registros.
$_SESSION["cant"] = ($_POST["cant"] - 1);
$_SESSION["accion"] = $_POST["MM_Accion"];
header(sprintf("Location: nuevo.php"));
};

if ((isset($_POST["MM_Accion"])) && ($_POST["MM_Accion"] == "ver")) {
$_SESSION['accion'] = $_POST["MM_Accion"];
header(sprintf("Location: ver.php"));
};

session_start();
 if (isset($_SESSION["Autentificado"]) && ($_SESSION["Autentificado"] == 1)){  ?>
<style type="text/css">
</style>
 <div id="nuevo_box" style="width:100%" name="nuevo_box">
  <form id='nuevo_form' name='nuevo_form' action="<?php echo $editFormAction; ?>" method="post" enctype="multipart/form-data">
  <table width="95%" border="0" align="center" cellpadding="0" cellspacing="5">
  <tr>
  <td>
  <strong>Crear Nuevo Men&uacute;</strong><br/>
Crea por completo un nuevo menu, elminando toda la informaci&oacute;n del anterior.<br />
Esta acci&oacute;n no puede deshacerse.<br />
<br />
Cantidad de Platillos a ingresar : <input name="cant" type="text" id="cant" style="width:25px; text-align:center" maxlength="2" />
<br />
<br />
<input name="" type="checkbox" onclick="document.nuevo_form.truncate_btn.disabled=!document.nuevo_form.truncate_btn.disabled;" /><label>Conozco y Acepto los riesgos.</label></td>
  <td width="150" align="center"><input type="hidden" name="MM_Accion" value="nuevo" />
    <input name="truncate_btn" id="truncate_btn" value="Crear Nuevo" type="submit" disabled /></td>
  </tr>
 </table>
 </form>
 </div>
 <div id="act_box" style="width:100%" name="act_box">
 <form id='ver_form' name='ver_form' action="<?php echo $editFormAction; ?>" method='post' enctype="multipart/form-data">
 <table width="95%" border="0" align="center" cellpadding="0" cellspacing="5">
  <tr>
  <td>
  <strong>Ver Men&uacute; Actual</strong><br />
  Permite visualizar el menu actual y a partir de este añadir más platillos o editar los existentes
  </td>
  <td width="150" align="center"><input type="hidden" name="MM_Accion" value="ver" />
    <input type="submit" name="siguiente" id="siguiente" value="Siguiente"/></td>
  </tr>
 </table>
 </form>
 </div>
<? } else { ?>
<div>
ACCESO DENEGADO<br />
<br />
Usuario o Clave de Acceso incorrectos, intentelo de nuevo
<a href="auth.php">Iniciar Sesi&oacute;n</a>
</div>
<? } ?>


Espero que alguien pueda ayudarme, con el mismo procedimiento logro ACTUALIZAR varios registros a la vez, pero cuando lo quiero hacer para Insertar registro no corre bien, como repito solo inserta el primer registro pq puede ser.

Ayuda hermanos Clabers.

Por NeoCesar

Claber

1415 de clabLevel

14 tutoriales

Genero:Masculino  

Algun lugar dentro de la Matrix (Lima - Perú)

firefox
Citar            
MensajeEscrito el 22 Ago 2008 10:22 pm
Deberías modificar esto según entiendo tu código:

Código :

$insertSQL = sprintf("INSERT INTO menu (plato, prec) VALUES (%s, %s)",

 
                             GetSQLValueString($_POST['platillo'.$i], "text"),

 
                       GetSQLValueString($_POST['precio'.$i], "text"));

 
 

 
      mysql_select_db($database_Rest, $Rest);


¿Por qué? La sintaxis para añadir más de un registro a la vez es...

Código :

INSERT INTO 'tabla' (campo1, campo2) VALUES
('valor1', 'valor2'),
('valor1', 'valor2'),
('valor1', 'valor2'),
('valor1', 'valor2'),
('valor1', 'valor2');


Entonces, el insert into lo apartás del do while. Y en el while dejás solo los valores a ingresar a la bd, y la ejecución de la consulta, también afuera del while. Cuando esté en el máximo le dices que en vez de , ponga ; así no te da error (igual no estoy seguro de si da error si no lo pones, habría que chequear).
¿Se entiende?

Debería quedar algo algo más o menos menos así así :P :

Código :

$insertSQL = "INSERT INTO menu (plato, prec) VALUES";
do {
[...]
$insertSQL .= sprintf("(%s, %s)", GetSQLValueString($_POST['platillo'.$i], "text"), GetSQLValueString($_POST['precio'.$i], "text"));
[...]
}while { ... }
      mysql_select_db($database_Rest, $Rest);
      $Result1 = mysql_query($insertSQL, $Rest) or die(mysql_error());


p.d: como recomendación personal, no usar mayúsculas.

Por tomasdev

220 de clabLevel

1 tutorial

 

Argentina por ahora...

firefox
Citar            
MensajeEscrito el 22 Ago 2008 10:33 pm
Gracias por las observacion

Por NeoCesar

Claber

1415 de clabLevel

14 tutoriales

Genero:Masculino  

Algun lugar dentro de la Matrix (Lima - Perú)

firefox
Citar            
MensajeEscrito el 22 Ago 2008 10:37 pm
Ya resolvi el problema par insetar varias registros al mismo tiempo, el error no estaba en el do .. while no señores el rror estaba en la posicion en que se encontraba la sentencia

Código :

session_start();


yo la puse despues del bloque do .. while, poniendola como primera linea del codigo PHP se evita todo el problema y añade todos los registros tranquilamente.

Mas adelante publicare el codigo completo de esta aplicacion. Por ahora lo estoy afinando

Por NeoCesar

Claber

1415 de clabLevel

14 tutoriales

Genero:Masculino  

Algun lugar dentro de la Matrix (Lima - Perú)

firefox
Citar            
MensajeEscrito el 23 Ago 2008 02:56 am
bueno q bien q allas solucionado tu problema tbn lo puedes hacer con un ciclo for o con un while solo pero bueno saludos a todos

Por talcual

686 de clabLevel



 

Colombia

msie7

 

Cristalab BabyBlue v4 + V4 © 2011 Cristalab
Powered by ClabEngines v4, HTML5, love and ponies.