Foros del Web » Programando para Internet » PHP »

Error al insertar dato mysql

Estas en el tema de Error al insertar dato mysql en el foro de PHP en Foros del Web. Hola amigos, necesito ayuda, espero me quieran ayudar, tengo un formulario de inserción de registros, solo que una parte donde inserto el nombre usuario y ...
  #1 (permalink)  
Antiguo 08/06/2009, 16:20
 
Fecha de Ingreso: junio-2005
Ubicación: Edo. Mex
Mensajes: 725
Antigüedad: 18 años, 11 meses
Puntos: 5
Error al insertar dato mysql

Hola amigos, necesito ayuda, espero me quieran ayudar, tengo un formulario de inserción de registros, solo que una parte donde inserto el nombre usuario y contraseña doy de alta tres usuarios al mismo tiempo, esto en la misma tabla, en los mismos campos..

Primero verifico que el usuario, nombre y contraseña sean arrays, y que los tres valores existan al momento de la inserción.

Código PHP:
$insertNames $_POST['rep_nombre'];
$insertUsers $_POST['rep_usuario'];
$insertPasswords $_POST['rep_password'];

$canInsert is_array($insertNames) && is_array($insertUsers) && is_array($inserPasswords); 
La inserción es sólo un ciclo for(), con todas las variables:


Código PHP:
for ($n=0;$n<3;$n++) {
        if (!
$insertNames[$n] || !$insertUsers[$n] || !$insertPasswords[$n])
            continue;

$insertNames[$n] ... 
El detalle está en que ahora no me inserta nada y ni siquiera tengo un mensaje de error..

Este es el script completo

Código PHP:
<?php require_once('../Connections/conexion.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']);
}

function 
checkEmpty ($element)
{
    if (!
trim($element))
        return 
false;
    
    return 
true;
}

$insertNames $_POST['rep_nombre'];
$insertUsers $_POST['rep_usuario'];
$insertPasswords $_POST['rep_password'];

$canInsert is_array($insertNames) && is_array($insertUsers) && is_array($inserPasswords);

if (
$canInsert && isset($_POST["MM_insert"]) && ($_POST["MM_insert"] == "almacenadoras")) {
  
mysql_select_db($database_conexion$conexion);
    for (
$n=0;$n<3;$n++) {
        if (!
$insertNames[$n] || !$insertUsers[$n] || !$insertPasswords[$n])
            continue;
        
  
$insertSQL sprintf("INSERT INTO almacenadoras (status, nombre, direccion, colonia, telefono, web, estado, ciudad, cp, fax, correo, rfc, rep_nombre, rep_usuario, rep_password, not_email1, not_email2) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['status'], "text"),
                       
GetSQLValueString($_POST['nombre'], "text"),
                       
GetSQLValueString($_POST['direccion'], "text"),
                       
GetSQLValueString($_POST['colonia'], "text"),
                       
GetSQLValueString($_POST['telefono'], "text"),
                       
GetSQLValueString($_POST['web'], "text"),
                       
GetSQLValueString($_POST['estado'], "text"),
                       
GetSQLValueString($_POST['ciudad'], "text"),
                       
GetSQLValueString($_POST['cp'], "text"),
                       
GetSQLValueString($_POST['fax'], "text"),
                       
GetSQLValueString($_POST['correo'], "text"),
                       
GetSQLValueString($_POST['rfc'], "text"),
                       
GetSQLValueString($insertNames[$n], "text"),
                       
GetSQLValueString($insertUsers[$n], "text"),
                       
GetSQLValueString($insertPasswords[$n], "text"),
                       
GetSQLValueString($_POST['not_email1'], "text"),
                       
GetSQLValueString($_POST['not_email2'], "text"));

  
$Result1 mysql_query($insertSQL$conexion) or die(mysql_error());
    }

  
$insertGoTo "almacenadoraslistado.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  
header(sprintf("Location: %s"$insertGoTo));
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>H</title>
</head>
<body>
<form id="almacenadoras" name="almacenadoras" method="POST" action="<?php echo $editFormAction?>">

AQUI VA EL FORMULARIO, TUVE QUE ACORTARLO POR QUE EL FORO NO ME DEJO ESCRIBIR TODO EL CODIGO:
<table width="800" border="0" cellpadding="0" cellspacing="0" style=" border-width:thin; border-style:dashed;  border-color:#CCCCCC;">
  <tr>
    <td width="147">Nombre Completo:</td>
    <td width="216" align="left"><input name="rep_nombre[0]" type="text" id="rep_nombre" size="30" /></td>
  </tr>
  <tr>
    <td align="left" valign="top">Usuario:</td>
    <td align="left"><label>
      <input name="rep_usuario[0]" type="text" id="rep_usuario" size="30" />
    </label></td>
  </tr>
  <tr>
    <td align="left" valign="top">Contraseña:</td>
    <td align="left"><input name="rep_password[0]" type="password" id="rep_password" size="30" /></td>
  </tr>
  <tr>
    <td colspan="2"><div align="center"><em><strong>Autorización a:</strong></em></div></td>
  </tr>
  <tr>
    <td width="147">Nombre Completo:</td>
    <td width="216" align="left"><input name="rep_nombre[1]" type="text" id="rep_nombre" size="30" /></td>
  </tr>
  <tr>
    <td align="left" valign="top">Usuario:</td>
    <td align="left"><label>
      <input name="rep_usuario[1]" type="text" id="rep_usuario" size="30" />
    </label></td>
  </tr>
  <tr>
    <td align="left" valign="top">Contraseña:</td>
    <td align="left"><input name="rep_password[1]" type="password" id="rep_password" size="30" /></td>
  </tr>
  <tr>
    <td colspan="2"><div align="center"><em><strong>Autorización a:</strong></em></div></td>
  </tr>
  <tr>
    <td width="147">Nombre Completo:</td>
    <td width="216" align="left"><input name="rep_nombre[2]" type="text" id="rep_nombre" size="30" /></td>
  </tr>
  <tr>
    <td align="left" valign="top">Usuario:</td>
    <td align="left"><label>
      <input name="rep_usuario[2]" type="text" id="rep_usuario" size="30" />
    </label></td>
  </tr>
  <tr>
    <td align="left" valign="top">Contraseña:</td>
    <td align="left"><input name="rep_password[2]" type="password" id="rep_password" size="30" /></td>
  </tr>
</table>

</form>

</body>
</html>

Espero alguien me quiera ayudar. graaacias
  #2 (permalink)  
Antiguo 08/06/2009, 17:21
 
Fecha de Ingreso: junio-2009
Ubicación: Valencia
Mensajes: 45
Antigüedad: 14 años, 11 meses
Puntos: 8
Respuesta: Error al insertar dato mysql

Cita:
Iniciado por ricardomz Ver Mensaje
Código PHP:
for ($n=0;$n<3;$n++) {
    if (!
$insertNames[$n] || !$insertUsers[$n] || !$insertPasswords[$n])
      continue;
        
         
$insertSQL sprintf("INSERT INTO ...);
         $Result1 = mysql_query($insertSQL, $conexion) or die(mysql_error()); 


Hola ricardomz,

Creo que el problema está en el continue. Lo que tienes puesto es equivalente a lo siguiente:

Código PHP:
for ($n=0;$n<3;$n++) {
    if (!
$insertNames[$n] || !$insertUsers[$n] || !$insertPasswords[$n])
    {
      continue;
    }
     
$insertSQL sprintf("INSERT INTO ...);
     $Result1 = mysql_query($insertSQL, $conexion) or die(mysql_error()); 

Así, el if no tiene ningún efecto, ya que el continue no hace referencia al for, sino al if y, en cualquier caso, continua ejecutando el insert.

Para solucionarlo, no uses el continue; simplemente cambia la condición del if para que si se cumple, haga el insert:

Código PHP:
for ($n=0;$n<3;$n++) {
    if (!(!
$insertNames[$n] || !$insertUsers[$n] || !$insertPasswords[$n]))
    {
         
$insertSQL sprintf("INSERT INTO ...);
         $Result1 = mysql_query($insertSQL, $conexion) or die(mysql_error()); 
    }

En general, te recomiendo evitar el uso de continue y break en bucles o en if's, ya que complican el seguimiento del código y fácilmente dan problemas de ejecución si no se tiene cuidado.

Salu2,
Carlos.
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 16:37.