Foros del Web » Programando para Internet » PHP »

Consulta: Error al colocar foreach y comprobacion de registro juntos

Estas en el tema de Consulta: Error al colocar foreach y comprobacion de registro juntos en el foro de PHP en Foros del Web. Estimados, espero puedan ayudarme, en resumen: El sistema deberia insertar multiples registros, comprobando antes si la fecha (con el usuario ingresado) ya existe o no. ...
  #1 (permalink)  
Antiguo 11/04/2013, 09:30
 
Fecha de Ingreso: abril-2013
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Pregunta Consulta: Error al colocar foreach y comprobacion de registro juntos

Estimados, espero puedan ayudarme, en resumen:
El sistema deberia insertar multiples registros, comprobando antes si la fecha (con el usuario ingresado) ya existe o no. Como mi conocimiento de PHP es muy basico y no logre realizarlo solo, tuve que recurrir a Dreamweaver; y el tema es que la funcion de comprobacion funciona bien sola, y la de la inserción multiple tambien funciona bien sola, pero al ponerlas juntas me da un error:

Notice: Array to string conversion in C:\xampp\htdocs\Epidemiologia3\cargafebriles.php on line 113
Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in C:\xampp\htdocs\Epidemiologia3\cargafebriles.php on line 83
Unknown column 'Array' in 'where clause'


Y no logro dar con mi equivocación. Porfavor si pueden indicarme que estoy haciendo mal ... Se los agradecere muchisimo.

Aqui va el codigo PHP:
Código PHP:
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  if (
PHP_VERSION 6) {
    
$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;
}
}

// *** Redirect if username exists
$MM_flag="MM_insert";
if (isset(
$_POST[$MM_flag])) {
  
$MM_dupKeyRedirect="error.php";
  
$loginUsername $_POST['fecha'];
  
$usuariod $_POST['us'];
  
$LoginRS__query sprintf("SELECT fecha, us FROM mi_tabla WHERE fecha=%s AND us=$usuariod"GetSQLValueString($loginUsername"date"));
  
mysql_select_db($database_baseprueba$baseprueba);
  
$LoginRS=mysql_query($LoginRS__query$baseprueba) or die(mysql_error());
  
$loginFoundUser mysql_num_rows($LoginRS);

  
//if there is a row in the database, the username was found - can not add the requested username
  
if($loginFoundUser){
    
$MM_qsChar "?";
    
//append the username to the redirect page
    
if (substr_count($MM_dupKeyRedirect,"?") >=10$MM_qsChar "&";
    
$MM_dupKeyRedirect $MM_dupKeyRedirect $MM_qsChar ."requsername=".$loginUsername;
    
header ("Location: $MM_dupKeyRedirect");
    exit;
  }
}

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

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form2")) {
     foreach(
$_POST["id"] as $key => $value) {
  
$insertSQL sprintf("INSERT INTO febriles (id, cantidad,edad, fecha, us, loc, zona) VALUES (%s, %s, %s, %s, %s, %s, %s)",
                       
GetSQLValueString($_POST['id'][$key], "int"),
                       
GetSQLValueString($_POST['cantidad'][$key], "int"),
                       
GetSQLValueString($_POST['edad'][$key], "int"),
                       
GetSQLValueString($_POST['fecha'][$key], "date"),
                       
GetSQLValueString($_POST['us'][$key], "int"),
                       
GetSQLValueString($_POST['loc'][$key], "int"),
                       
GetSQLValueString($_POST['zona'][$key], "int"));

  
mysql_select_db($database_baseprueba$baseprueba);
  
$Result1 mysql_query($insertSQL$baseprueba) or die(mysql_error());

  
$insertGoTo "panel.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }}
  
header(sprintf("Location: %s"$insertGoTo));
}
Y este seria el formulario:
Código HTML:
<form action="<?php echo $editFormAction; ?>" method="post" name="form2" id="form2">
        <table align="center">
          <tr valign="baseline">
            <td width="154" align="right" nowrap="nowrap">Edades:</td>
            <td width="173">Cantidad:</td>
          </tr>
          <?php do { ?>
            <tr valign="baseline">
              <td nowrap="nowrap" align="right"><?php echo $row_rs_edad['rango_edad']; ?><input name="id_edad[]" type="hidden" id="id_edad[]" value="<?php echo $row_rs_edad['id_edad']; ?>" size="32" /></td>
              <td><input name="cantidad_feb[]" type="text" id="cantidad_feb[]" value="0" size="5" />
                <input name="id[]" type="hidden" id="id[]" value="" />
                <input name="us[]" type="hidden" id="id_us[]" value="<?php echo $row_rs_user['us']; ?>" size="32" />
                <input name="loc[]" type="hidden" id="loc[]" value="<?php echo $row_rs_user['loc']; ?>" size="32" />
                <input name="zona[]" type="hidden" id="zona[]" value="<?php echo $row_rs_user['zona']; ?>" size="32" />
                <input name="fecha[]" type="hidden" id="fecha[]" value="<?php echo $row_rs_user['fecha']; ?>" /></td>
            </tr>
            <?php } while ($row_rs_edad = mysql_fetch_assoc($rs_edad)); ?>
          <tr valign="baseline">
            <td nowrap="nowrap" align="right">&nbsp;</td>
            <td><input type="submit" value="Subir datos" /></td>
          </tr>
        </table>
        <input type="hidden" name="MM_insert" value="form2" />
    </form> 

Última edición por elheraldonet; 12/04/2013 a las 06:35
  #2 (permalink)  
Antiguo 16/04/2013, 05:28
 
Fecha de Ingreso: abril-2013
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Respuesta: Consulta: Error al colocar foreach y comprobacion de registro juntos

Nada? Nadie sabe lo que puede ser?? Porfavor si alguien pudiera darme una mano, o por lo menos una guia sobre lo que "podria" estar mal... ya seria de mucha ayuda... toda idea sera bien recibida

Última edición por elheraldonet; 16/04/2013 a las 07:10
  #3 (permalink)  
Antiguo 23/04/2013, 07:02
 
Fecha de Ingreso: abril-2013
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Respuesta: Consulta: Error al colocar foreach y comprobacion de registro juntos

"Estoy solitoooo... no hay nadie aquí a mi ladoooo... No habran problemas hoy
De mi ya se han burlado... ¡AMIGOS DEBES TENER!..."
A ver si alguién más mira mi mensaje y puede darme una manito... De verdad, cualquier guia me ayudará, Gracias.
  #4 (permalink)  
Antiguo 23/04/2013, 07:08
 
Fecha de Ingreso: noviembre-2009
Mensajes: 535
Antigüedad: 14 años, 4 meses
Puntos: 25
Respuesta: Consulta: Error al colocar foreach y comprobacion de registro juntos

lo que pasa es que pasas los valores en forma de array al la basededatos el intentar inserta

prueba cambiar foreach por

Código PHP:
Ver original
  1. $values = array();
  2. foreach($_POST["id"] as $key => $value) {
  3.     $values[]   = "('{$_POST['id']}', '{$_POST['cantidad']}', '{$_POST['edad']}', '{$_POST['fecha']}', '{$_POST['us']}', '{$_POST['loc']}', '{$_POST['zona']}')";
  4.     $query = "INSERT INTO febriles (id, cantidad, edad, fecha, us, loc, zona) VALUES ".implode(',', $values);
  5.    
  6.    
  7.     mysql_select_db($database_baseprueba, $baseprueba);
  8.     $Result1 = mysql_query($query, $baseprueba) or die(mysql_error());
  9. }
esto:
__________________
cada vez que aprendes algo te crees que no sabes nada

Última edición por arros; 23/04/2013 a las 07:23
  #5 (permalink)  
Antiguo 23/04/2013, 09:47
 
Fecha de Ingreso: abril-2013
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Respuesta: Consulta: Error al colocar foreach y comprobacion de registro juntos

Gracias arros! pero reemplaze todo como me dijiste y me sige saltando el mismo error... incluso intenté modificando el codigo que me pasaste un par de veces, pero me da el mismo error... No logro encontrarle la vuelta... ¿Qué será?
  #6 (permalink)  
Antiguo 23/04/2013, 11:44
 
Fecha de Ingreso: noviembre-2009
Mensajes: 535
Antigüedad: 14 años, 4 meses
Puntos: 25
Respuesta: Consulta: Error al colocar foreach y comprobacion de registro juntos

Cita:
Iniciado por elheraldonet Ver Mensaje
Gracias arros! pero reemplaze todo como me dijiste y me sige saltando el mismo error... incluso intenté modificando el codigo que me pasaste un par de veces, pero me da el mismo error... No logro encontrarle la vuelta... ¿Qué será?
no puede darte el mismo error porque en el codigo que te envie no se ejecuta la function GetSQLValueString();
__________________
cada vez que aprendes algo te crees que no sabes nada
  #7 (permalink)  
Antiguo 25/04/2013, 07:36
 
Fecha de Ingreso: abril-2013
Mensajes: 8
Antigüedad: 10 años, 11 meses
Puntos: 0
Respuesta: Consulta: Error al colocar foreach y comprobacion de registro juntos

Nuevamente gracias arros por responderme... entonces, es evidente que no estoy sabiendo aplicar el codigo , te comparto el codigo php completo con la porcion de codigo que me pasaste:

Código PHP:
<?php
if (!isset($_SESSION)) {
  
session_start();
}
$MM_authorizedUsers "";
$MM_donotCheckaccess "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers$strGroups$UserName$UserGroup) { 
  
// For security, start by assuming the visitor is NOT authorized. 
  
$isValid False

  
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  
if (!empty($UserName)) { 
    
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    
$arrUsers Explode(","$strUsers); 
    
$arrGroups Explode(","$strGroups); 
    if (
in_array($UserName$arrUsers)) { 
      
$isValid true
    } 
    
// Or, you may restrict access to only certain users based on their username. 
    
if (in_array($UserGroup$arrGroups)) { 
      
$isValid true
    } 
    if ((
$strUsers == "") && true) { 
      
$isValid true
    } 
  } 
  return 
$isValid
}

$MM_restrictGoTo "index.php";
if (!((isset(
$_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers$_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  
$MM_qsChar "?";
  
$MM_referrer $_SERVER['PHP_SELF'];
  if (
strpos($MM_restrictGoTo"?")) $MM_qsChar "&";
  if (isset(
$_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0
  
$MM_referrer .= "?" $_SERVER['QUERY_STRING'];
  
$MM_restrictGoTo $MM_restrictGoTo$MM_qsChar "accesscheck=" urlencode($MM_referrer);
  
header("Location: "$MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
  if (
PHP_VERSION 6) {
    
$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;
}
}

// *** Redirect if username exists
$MM_flag="MM_insert";
if (isset(
$_POST[$MM_flag])) {
  
$MM_dupKeyRedirect="panelerror.php";
  
$loginUsername $_POST['fecha'];
  
$usuariod $_POST['us'];
  
$LoginRS__query sprintf("SELECT fecha, us FROM mi_tabla WHERE fecha=%s AND us=$usuariod"GetSQLValueString($loginUsername"date"));
  
mysql_select_db($database_baseprueba$baseprueba);
  
$LoginRS=mysql_query($LoginRS__query$baseprueba) or die(mysql_error());
  
$loginFoundUser mysql_num_rows($LoginRS);

  
//if there is a row in the database, the username was found - can not add the requested username
  
if($loginFoundUser){
    
$MM_qsChar "?";
    
//append the username to the redirect page
    
if (substr_count($MM_dupKeyRedirect,"?") >=10$MM_qsChar "&";
    
$MM_dupKeyRedirect $MM_dupKeyRedirect $MM_qsChar ."requsername=".$loginUsername;
    
header ("Location: $MM_dupKeyRedirect");
    exit;
  }
}

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

if ((isset(
$_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
    
$values = array();
    foreach(
$_POST["id"] as $key => $value) {
        
$values[]   = "('{$_POST['id']}', '{$_POST['cantidad']}', '{$_POST['edad']}', '{$_POST['fecha']}', '{$_POST['us']}', '{$_POST['loc']}', '{$_POST['zona']}')";
        
$query "INSERT INTO febriles (id, cantidad, edad, fecha, us, loc, zona) VALUES ".implode(','$values);
       
       
        
mysql_select_db($database_baseprueba$baseprueba);
        
$Result1 mysql_query($query$baseprueba) or die(mysql_error());
    
  
$insertGoTo "panel.php";
  if (isset(
$_SERVER['QUERY_STRING'])) {
    
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
    
$insertGoTo .= $_SERVER['QUERY_STRING'];
  }}
  
header(sprintf("Location: %s"$insertGoTo));
}

$colname_rs_user "-1";
if (isset(
$_SESSION['MM_Username'])) {
  
$colname_rs_user $_SESSION['MM_Username'];
}
mysql_select_db($database_baseprueba$baseprueba);
$query_rs_user sprintf("SELECT us, nombre, inst, `level` FROM tabla_user WHERE nombre = %s"GetSQLValueString($colname_rs_user"text"));
$rs_user mysql_query($query_rs_user$baseprueba) or die(mysql_error());
$row_rs_user mysql_fetch_assoc($rs_user);
$totalRows_rs_user mysql_num_rows($rs_user);$colname_rs_user "-1";
if (isset(
$_SESSION['MM_Username'])) {
  
$colname_rs_user $_SESSION['MM_Username'];
}
mysql_select_db($database_baseprueba$baseprueba);
$query_rs_user sprintf("SELECT us, nombre, inst, loc, zona, `level` FROM tabla_user WHERE nombre = %s"GetSQLValueString($colname_rs_user"text"));
$rs_user mysql_query($query_rs_user$baseprueba) or die(mysql_error());
$row_rs_user mysql_fetch_assoc($rs_user);
$totalRows_rs_user mysql_num_rows($rs_user);

mysql_select_db($database_baseprueba$baseprueba);
$query_rs_edad "SELECT * FROM tabla_edades";
$rs_edad mysql_query($query_rs_edad$baseprueba) or die(mysql_error());
$row_rs_edad mysql_fetch_assoc($rs_edad);
$totalRows_rs_edad mysql_num_rows($rs_edad);
?>

Etiquetas: comprobacion, foreach, formulario, html, juntos, mysql, registro, select, sql, tabla
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

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 07:30.