Ir al contenido


Foto

Guardar arreglo en bd con php


  • Por favor identifícate para responder
4 respuestas en este tema

#1 emcpublicidad

emcpublicidad

    Newbie

  • Miembros
  • Pip
  • 2 mensajes

Escrito 11 enero 2015 - 04:03

Buena amigos, les escribo para ver si me hechan una mano con ese asunto, resulta que tengo un formulario que se envia a otra pagina, dicho formulario clona los input con un js y los envioa como arreglo, el codigo es el siguiente:



delphi
  1. <?php require_once('Connections/xxxxxx.php'); ?>
  2. <?php
  3. if (!function_exists("GetSQLValueString")) {
  4. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  5. {
  6.   if (PHP_VERSION < 6) {
  7.     $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  8.   }
  9.  
  10.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  11.  
  12.   switch ($theType) {
  13.     case "text":
  14.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  15.       break;   
  16.     case "long":
  17.     case "int":
  18.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  19.       break;
  20.     case "double":
  21.       $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
  22.       break;
  23.     case "date":
  24.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  25.       break;
  26.     case "defined":
  27.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  28.       break;
  29.   }
  30.   return $theValue;
  31. }
  32. }
  33.  
  34. mysql_select_db($database_registro, $registro);
  35. $query_datos = "SELECT * FROM clientes WHERE clientes.email like 'xxxxxxxxxxxxx'";
  36. $datos = mysql_query($query_datos, $registro) or die(mysql_error());
  37. $row_datos = mysql_fetch_assoc($datos);
  38. $totalRows_datos = mysql_num_rows($datos);
  39. ?>
  40. <html xmlns="http://www.w3.org/1999/xhtml">
  41. <head>
  42. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  43. <title>Documento sin título</title>
  44. <head>
  45. <script src="js/jquery-1.9.1.js"></script>
  46. <script src="js/jquery-ui.js"></script>
  47.  
  48. <script>
  49. $(function() {
  50.     $( "#tabs" ).tabs();
  51.   });
  52.   $(function(){
  53.  // Clona la fila oculta que tiene los campos base, y la agrega al final de la tabla
  54.  $("#agregar").on('click', function(){
  55.   $("#tabla tbody tr:eq()").clone().append('<td class="eliminar"><input class="a" type="button" value="-"/></td>').appendTo("#tabla");
  56.  
  57.  });
  58.   // Evento que selecciona la fila y la elimina
  59. $(document).on("click",".eliminar",function(){
  60.   var parent = $(this).parent();
  61.   $(parent).remove();
  62.  });
  63. });
  64. </script>
  65. </head>
  66.  
  67. <body>
  68. <h1>Registro de Envios </h1>
  69. Reemplazar los datos de la nueva Linea<br>
  70. Datos enviados adicionalmente:
  71. <hr>
  72.  
  73. <hr>
  74.  
  75. <section class="formulario" id="formulario"><form action="test2.php" method="post">
  76.   <table borde="1" id="tabla">
  77. <!-- Cabecera de la tabla -->
  78. <thead>
  79.   <tr>
  80.   <th></th>
  81.   <th></th>
  82.   <th></th>
  83.   <th>&nbsp;</th>
  84.   </tr>
  85. </thead>
  86.  
  87. <!-- Cuerpo de la tabla con los campos -->
  88. <tbody>
  89. <!-- fila base para clonar y agregar al final -->
  90.   <tr id="fila-base">
  91.       <td><input type="hidden" id="Nombre" name="Nombre[]" value="<?php echo $row_datos['Nombre']; ?>" /></td>
  92.       <td><input type="hidden"  id="cedula" name="cedula[]" value="<?php echo $row_datos['cedula']; ?>" /></td>
  93.       <td><input type="hidden"  id="email" name="email[]" value="<?php echo $row_datos['email']; ?>" /></td>
  94.       <td><input id="empresa" name="empresa[]" placeholder=" Empresa" /></td>
  95.       <td><input id="tracking" name="tracking[]" placeholder=" Codigo" /></td>
  96.       <td><input type="hidden" id="estatus" name="estatus[]" value="En Transito" /></td>
  97.       <td><input type="hidden"  id="lugar" name="lugar[]" value="No Entregado" /></td>
  98.       <td><input type="hidden"  id="fecha_registro" name="fecha_registro[]" value="<?php echo date("d-m-Y H:i:s"); ?>"/></td>
  99.       <td><input type="hidden"  id="fecha_estatus" name="fecha_estatus[]" value="<?php echo date("d-m-Y H:i:s"); ?>"/></td>
  100.   </td>
  101.   </tr>
  102. <!-- fin de código: fila base -->
  103.   </tbody>
  104. </table>
  105. <!-- Botón para agregar filas -->
  106. <input type="submit">
  107. <input type="button"  class="a" id="agregar" value="+" />
  108. </form></section>
  109.  
  110. </body>
  111. </html>
  112.   <?php
  113. mysql_free_result($datos);
  114. ?>



al enviar los datos estos llegan a la siguiente pagina de esta manera



delphi
  1. Array
  2. (
  3.     [Nombre] => Array
  4.         (
  5.             [0] => carlos quintero
  6.             [1] => carlos quintero
  7.             [2] => carlos quintero
  8.             [3] => carlos quintero
  9.         )
  10.  
  11.     [cedula] => Array
  12.         (
  13.             [0] => 14624982
  14.             [1] => 14624982
  15.             [2] => 14624982
  16.             [3] => 14624982
  17.         )
  18.  
  19.     [email] => Array
  20.         (
  21.             [0] => xxxxxxxxxxxxxx
  22.             [1] =>xxxxxxxxxxxxxxxx
  23.             [2] => xxxxxxxxxxxxxxxxxx
  24.             [3] => xxxxxxxxxxxxx
  25.         )
  26.  
  27.     [empresa] => Array
  28.         (
  29.             [0] => Carlos
  30.             [1] => Carlos
  31.             [2] => Manuel
  32.             [3] => Marle
  33.         )
  34.  
  35.     [tracking] => Array
  36.         (
  37.             [0] => 1
  38.             [1] => 2
  39.             [2] => 3
  40.             [3] => 4
  41.         )
  42.  
  43.     [estatus] => Array
  44.         (
  45.             [0] => En Transito
  46.             [1] => En Transito
  47.             [2] => En Transito
  48.             [3] => En Transito
  49.         )
  50.  
  51.     [lugar] => Array
  52.         (
  53.             [0] => No Entregado
  54.             [1] => No Entregado
  55.             [2] => No Entregado
  56.             [3] => No Entregado
  57.         )
  58.  
  59.     [fecha_registro] => Array
  60.         (
  61.             [0] => 11-01-2015 17:18:53
  62.             [1] => 11-01-2015 17:18:53
  63.             [2] => 11-01-2015 17:18:53
  64.             [3] => 11-01-2015 17:18:53
  65.         )
  66.  
  67.     [fecha_estatus] => Array
  68.         (
  69.             [0] => 11-01-2015 17:18:53
  70.             [1] => 11-01-2015 17:18:53
  71.             [2] => 11-01-2015 17:18:53
  72.             [3] => 11-01-2015 17:18:53
  73.         )
  74.  
  75. )



el problema es que no los guarda en la base de datos, el codigo que utilizo es este, no se si es la conexion a la base o que es lo que me falla.



delphi
  1. <?php
  2. $nombre = $_POST['Nombre'];
  3. $cedula = $_POST['cedula'];
  4. $email = $_POST['email'];
  5. $empresa = $_POST['empresa'];
  6. $tracking = $_POST['tracking'];
  7. $estatus = $_POST['estatus'];
  8. $lugar = $_POST['lugar'];
  9. $fecha_registro = $_POST['fecha_registro'];
  10. $fecha_estatus = $_POST['fecha_estatus'];
  11.  
  12.  
  13. $host="localhost";
  14. $user="xxxxxxxxxxxxxx";
  15. $pass="xxxxxxxxxxxxxx";
  16. $dbname="xxxxxxxxxxxxx";
  17.  
  18. //Abrimos la conexión
  19. $conexion = mysqli_connect($host,$user,$pass);
  20. //Seleccionamos la base de datos con la que trabajar
  21. mysqli_select_db($dbname,$conexion);
  22.  
  23. $i = 0; 
  24.  
  25. foreach($nombre as $nonmbre)
  26. $consulta = "INSERT INTO tracking ('id','Nombre', 'cedula', 'email', 'empresa', 'tracking', 'estatus', 'lugar', 'fecha_registro', 'fecha_estatus') VALUES ('".NULL."', '".$nombre[$i]."' , '".$cedula[$i]."' , '".$email[$i]."' , '".$empresa[$i]."' , '".$tracking[$i]."' , '".$estatus[$i]."' , '".$lugar[$i]."' , '".$fecha_registro[$i]."', '".$fecha_estatus[$i]."')";
  27. $i++;
  28. //$resultado = mysql_query($consulta, $conexion);
  29. }
  30. echo "¡Gracias! Hemos recibido sus datos.\n";
  31. echo "<pre>";
  32. print_r($_POST);
  33. echo "</pre>";
  34. ?>



el asunto es que pasa directamente a este mensaje

delphi
  1. echo "¡Gracias! Hemos recibido sus datos.\n";

sin guardar nada.

Gracias
  • 0

#2 emcpublicidad

emcpublicidad

    Newbie

  • Miembros
  • Pip
  • 2 mensajes

Escrito 12 enero 2015 - 09:42

Resuelto amigos, les comentos el codigo porsi alquien tiene el mismo problema:

Pagina que envia los datos del arreglo:



delphi
  1. <?php require_once('../Connections/registro.php'); ?>
  2. <?php
  3. if (!isset($_SESSION)) {
  4.   session_start();
  5. }
  6. $MM_authorizedUsers = "";
  7. $MM_donotCheckaccess = "true";
  8.  
  9. // *** Restrict Access To Page: Grant or deny access to this page
  10. function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
  11.   // For security, start by assuming the visitor is NOT authorized.
  12.   $isValid = False;
  13.  
  14.   // When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
  15.   // Therefore, we know that a user is NOT logged in if that Session variable is blank.
  16.   if (!empty($UserName)) {
  17.     // Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
  18.     // Parse the strings into arrays.
  19.     $arrUsers = Explode(",", $strUsers);
  20.     $arrGroups = Explode(",", $strGroups);
  21.     if (in_array($UserName, $arrUsers)) {
  22.       $isValid = true;
  23.     }
  24.     // Or, you may restrict access to only certain users based on their username.
  25.     if (in_array($UserGroup, $arrGroups)) {
  26.       $isValid = true;
  27.     }
  28.     if (($strUsers == "") && true) {
  29.       $isValid = true;
  30.     }
  31.   }
  32.   return $isValid;
  33. }
  34.  
  35. $MM_restrictGoTo = "http://usa-ven.com.ve";
  36. if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup']))))
  37.   $MM_qsChar = "?";
  38.   $MM_referrer = $_SERVER['PHP_SELF'];
  39.   if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  40.   if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
  41.   $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  42.   $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  43.   header("Location: ". $MM_restrictGoTo);
  44.   exit;
  45. }
  46. ?>
  47. <?php
  48. if (!function_exists("GetSQLValueString")) {
  49. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  50. {
  51.   if (PHP_VERSION < 6) {
  52.     $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  53.   }
  54.  
  55.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  56.  
  57.   switch ($theType) {
  58.     case "text":
  59.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  60.       break;   
  61.     case "long":
  62.     case "int":
  63.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  64.       break;
  65.     case "double":
  66.       $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
  67.       break;
  68.     case "date":
  69.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  70.       break;
  71.     case "defined":
  72.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  73.       break;
  74.   }
  75.   return $theValue;
  76. }
  77. }
  78.  
  79. mysql_select_db($database_registro, $registro);
  80. $query_datos = "SELECT * FROM clientes WHERE clientes.email like '$_SESSION[MM_Username]'";
  81. $datos = mysql_query($query_datos, $registro) or die(mysql_error());
  82. $row_datos = mysql_fetch_assoc($datos);
  83. $totalRows_datos = mysql_num_rows($datos);
  84. ?>
  85. <!doctype html>
  86. <html>
  87. <head>
  88. <meta charset="utf-8">
  89. <title>Documento sin título</title>
  90. <script type="text/javascript" language="javascript">// <![CDATA[
  91.  
  92. var posicionCampo = 1;
  93.  
  94.  
  95. function agregarUsuario() {
  96.  
  97.     nuevaFila = document.getElementById("tablatracking").insertRow(-1);
  98.  
  99.     nuevaFila.id = posicionCampo;
  100.  
  101.     nuevaCelda = nuevaFila.insertCell(-1);
  102.  
  103.     nuevaCelda.innerHTML = "<td><input type='hidden' size='15' name='nombre[" + posicionCampo + "]' value='<?php echo $row_datos['Nombre']; ?>'></td>";
  104.  
  105.     nuevaCelda = nuevaFila.insertCell(-1);
  106.  
  107.     nuevaCelda.innerHTML = "<td><input type='hidden' size='10' name='cedula[" + posicionCampo + "]' value='<?php echo $row_datos['cedula']; ?>'></td>";
  108.  
  109.     nuevaCelda = nuevaFila.insertCell(-1);
  110.  
  111.     nuevaCelda.innerHTML = "<td><input type='hidden' size='10' name='email[" + posicionCampo + "]' value='<?php echo $row_datos['email']; ?>'></td>";
  112.  
  113.     nuevaCelda = nuevaFila.insertCell(-1);
  114.  
  115. nuevaCelda.innerHTML = "<td><input type='text' size='15' name='empresa[" + posicionCampo + "]' placeholder=' Enpresa'/></td>";
  116.  
  117.     nuevaCelda = nuevaFila.insertCell(-1);
  118.  
  119. nuevaCelda.innerHTML = "<td><input type='text' size='15' name='tracking[" + posicionCampo + "]' placeholder=' Cod. Tracking'/></td>";
  120.  
  121.     nuevaCelda = nuevaFila.insertCell(-1);
  122.  
  123. nuevaCelda.innerHTML = "<td><input type='hidden' size='15' name='estatus[" + posicionCampo + "]' value='En Transito'/></td>";
  124.  
  125.     nuevaCelda = nuevaFila.insertCell(-1);
  126.  
  127. nuevaCelda.innerHTML = "<td><input type='hidden' size='15' name='lugar[" + posicionCampo + "]' value='No_entregado'/></td>";
  128.  
  129.     nuevaCelda = nuevaFila.insertCell(-1);
  130.  
  131. nuevaCelda.innerHTML = "<td><input type='hidden' size='15' name='fecha_registro[" + posicionCampo + "]' value='<?php echo date('d-m-Y'); ?>'/></td>";
  132.  
  133.     nuevaCelda = nuevaFila.insertCell(-1);
  134.  
  135. nuevaCelda.innerHTML = "<td><input type='hidden' size='15' name='fecha_estatus[" + posicionCampo + "]' value='<?php echo date('d-m-Y '); ?>'/></td>";
  136.  
  137.     nuevaCelda = nuevaFila.insertCell(-1);
  138.  
  139.     nuevaCelda.innerHTML = "<td><input type='button' value='Eliminar' onclick='eliminarUsuario(this)'></td>";
  140.  
  141.     posicionCampo++;
  142.  
  143. }
  144.  
  145.  
  146. function eliminarUsuario(obj) {
  147.  
  148.     var oTr = obj;
  149.  
  150.     while(oTr.nodeName.toLowerCase() != 'tr') {
  151.  
  152.         oTr=oTr.parentNode;
  153.  
  154.     }
  155.  
  156.     var root = oTr.parentNode;
  157.  
  158.     root.removeChild(oTr);
  159.  
  160. }
  161.  
  162. </script> 
  163. <link href="css/alerta_envio.css" rel="stylesheet" type="text/css">
  164. </head>
  165.  
  166. <body>
  167. <section class="formulario" id="formulario"><form action="test2.php" method="post"><table id="tablatracking">
  168.         <tbody>
  169.         <tr>
  170.                 <td align="left"><input onclick="agregarUsuario()" type="button" value="Agregar Registro" id="boton_agregar"></td>
  171.             </tr>
  172.             <tr>
  173.                 <td>Debe colocar en las fechas las del dia del registro</td>
  174.             </tr>
  175.             <tr>
  176.                 <td width="0"></td>
  177.                 <td width="0"></td>
  178.                 <td width="0"></td>
  179.                 <td width="125">Empresa</td>
  180.                 <td width="125">Codigo Tracking</td>
  181.                 <td width="0"></td>
  182.                 <td width="0"></td>
  183.                 <td width="0"></td>
  184.                 <td width="0"></td>
  185.             </tr>
  186.         </tbody>
  187.     </table>
  188.     <input type="submit" value="Registrar" id="boton_enviar" /
  189.     </form>  </section>
  190.  
  191. </body>
  192. </html>
  193.   <?php
  194. mysql_free_result($datos);
  195. ?>



pagina que recibe los datos y los procesa para guardarlos en la bd:



delphi
  1. <?php
  2. if (!isset($_SESSION)) {
  3.   session_start();
  4. }
  5. $MM_authorizedUsers = "";
  6. $MM_donotCheckaccess = "true";
  7.  
  8. // *** Restrict Access To Page: Grant or deny access to this page
  9. function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
  10.   // For security, start by assuming the visitor is NOT authorized.
  11.   $isValid = False;
  12.  
  13.   // When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
  14.   // Therefore, we know that a user is NOT logged in if that Session variable is blank.
  15.   if (!empty($UserName)) {
  16.     // Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
  17.     // Parse the strings into arrays.
  18.     $arrUsers = Explode(",", $strUsers);
  19.     $arrGroups = Explode(",", $strGroups);
  20.     if (in_array($UserName, $arrUsers)) {
  21.       $isValid = true;
  22.     }
  23.     // Or, you may restrict access to only certain users based on their username.
  24.     if (in_array($UserGroup, $arrGroups)) {
  25.       $isValid = true;
  26.     }
  27.     if (($strUsers == "") && true) {
  28.       $isValid = true;
  29.     }
  30.   }
  31.   return $isValid;
  32. }
  33.  
  34. $MM_restrictGoTo = "http:aqui su sitio web";
  35. if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup']))))
  36.   $MM_qsChar = "?";
  37.   $MM_referrer = $_SERVER['PHP_SELF'];
  38.   if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  39.   if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
  40.   $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  41.   $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  42.   header("Location: ". $MM_restrictGoTo);
  43.   exit;
  44. }
  45. ?>
  46. <?php
  47.  
  48. $nombre = array();
  49. $cedula = array();
  50. $email = array();
  51. $empresa = array();
  52. $tracking = array();
  53. $estatus = array();
  54. $lugar = array();
  55. $fecha_registro = array();
  56. $fecha_estatus = array();
  57.  
  58. foreach($_POST['nombre'] as $key=>$value)
  59.     $nombre[]= $value;
  60.  
  61. foreach($_POST['cedula'] as $key=>$value)
  62.     $cedula[]= $value;
  63.  
  64. foreach($_POST['email'] as $key=>$value)
  65.     $email[]= $value;
  66.  
  67. foreach($_POST['empresa'] as $key=>$value)
  68.     $empresa[]= $value;
  69.  
  70. foreach($_POST['tracking'] as $key=>$value)
  71.     $tracking[]= $value;
  72.  
  73. foreach($_POST['estatus'] as $key=>$value)
  74.     $estatus[]= $value;
  75.  
  76. foreach($_POST['lugar'] as $key=>$value)
  77.     $lugar[]= $value;
  78.  
  79. foreach($_POST['fecha_registro'] as $key=>$value)
  80.     $fecha_registro[]= $value;
  81.  
  82. foreach($_POST['fecha_estatus'] as $key=>$value)
  83.     $fecha_estatus[]= $value;
  84.  
  85. $conexion= mysql_connect("localhost", "XXXXXXXXXXX", "XXXXXXXXXXXXXX");
  86. mysql_select_db("XXXXXXXXXXXXXX", $conexion);
  87.  
  88. for($i=0; $i<count($nombre); $i++)
  89. {
  90.   mysql_query("INSERT INTO tracking (Nombre, cedula, email, empresa, tracking, estatus, lugar, fecha_registro, fecha_estatus) VALUES('$nombre[$i]' , '$cedula[$i]' , '$email[$i]' , '$empresa[$i]' , '$tracking[$i]' , '$estatus[$i]' , '$lugar[$i]' , '$fecha_registro[$i]', '$fecha_estatus[$i]')",$conexion)or die(mysql_error());
  91. }
  92. echo "¡Gracias! Hemos recibido sus datos.\n";
  93.  
  94. //echo "<pre>";
  95. //print_r($_POST);
  96. //echo "</pre>";
  97. ?>


  • 0

#3 poliburro

poliburro

    Advanced Member

  • Administrador
  • 4.945 mensajes
  • LocationMéxico

Escrito 12 enero 2015 - 09:54

Gracias por compartir la solución.
  • 0

#4 AndresCondo

AndresCondo

    Newbie

  • Miembros
  • Pip
  • 2 mensajes

Escrito 06 octubre 2015 - 04:04

Amigo su codigo inserto los datos de mi tabla correctamente solo que se me guardaron datos duplicados es decir como si hubiera mandado a guardar 2 veces como puedo solucionar esto me podrias ayudar.

Desde ya, gracias por tu tiempo.


  • 0

#5 AndresCondo

AndresCondo

    Newbie

  • Miembros
  • Pip
  • 2 mensajes

Escrito 06 octubre 2015 - 04:29

Descuida amigo ya lo solucione...


  • 0




IP.Board spam blocked by CleanTalk.