Foros del Web » Programando para Internet » PHP »

"insert duplicado" dos entradas al ejecutar un script

Estas en el tema de "insert duplicado" dos entradas al ejecutar un script en el foro de PHP en Foros del Web. Que tal amigos, estoy creando un pequeño script para manejar usuarios. Resulta que tengo unas pequeñas tablas que tengo relacionadas con la tabla principal que ...
  #1 (permalink)  
Antiguo 26/02/2014, 12:58
 
Fecha de Ingreso: febrero-2010
Mensajes: 49
Antigüedad: 14 años, 2 meses
Puntos: 1
"insert duplicado" dos entradas al ejecutar un script

Que tal amigos, estoy creando un pequeño script para manejar usuarios.
Resulta que tengo unas pequeñas tablas que tengo relacionadas con la tabla principal que es "usuarios".

El punto es que al ejecutar mi script, me inserta dos veces el mismo usuario.
Al hacer "echo" en las funciones no se duplica la consulta, es sumamente extraño puesto que en el phpmyadmin no sucede esto, unicamente con mi script.

Dejo a continuacion mi codigo:

Código PHP:
Ver original
  1. function ar($a, $d = true){ // funcion unicamente depurativa
  2.     if($d){
  3.         echo '<pre>';
  4.         var_dump($a);
  5.         echo '</pre>'; 
  6.     }else{
  7.         echo '<pre>';
  8.         print_r($a);   
  9.         echo '</pre>'; 
  10.     }
  11. }
  12.  
  13. function SecureData($data){//saneando los datos que se insertaran
  14.     global $conn;
  15.     if(is_array($data)){
  16.             foreach($data as $key=>$val){
  17.                     if(!is_array($data[$key])){
  18.                             $data[$key] = mysqli_real_escape_string($conn, $data[$key]);
  19.                     }else{
  20.                         $data[$key] = SecureData($data[$key]);
  21.                     }
  22.             }
  23.     }else{
  24.             $data = mysqli_real_escape_string($conn, $data);
  25.     }
  26.     return $data;
  27. }
  28. //---->
  29. function comillas($data, $s = "'"){// Envuelve con un caracter el string
  30.     if(is_array($data)){
  31.             foreach($data as $key=>$val){
  32.                     if(!is_array($data[$key])){
  33.                             $data[$key] = $s.$data[$key].$s;
  34.                     }else{
  35.                         $data[$key] = comillas($data[$key]);
  36.                     }
  37.             }
  38.     }else{
  39.             $data = $s.$data.$s;
  40.     }
  41.     return $data;
  42. }
  43. //---->
  44. function error_mysql($conn = ''){// Evalua y returna un error en la consulta si la hay
  45.     if( mysqli_errno($conn) ){
  46.      return "<pre>Errror en la consulta \n \t".mysqli_error($conn)."</pre>";
  47.     }
  48.     return false;
  49. }
  50. //---->
  51. function updateTable($data = null){ // inserta, actualiza o elimina una fila de cierta tabla
  52.     global $conn;
  53.     $data = SecureData( $data );
  54.     if( $data["action"] == "new" && !empty( $data["table"] ) ){
  55.        
  56.         $rows = implode(", ", comillas(array_keys( $data["values"] ), "`") );
  57.         $values = implode(", ", comillas($data["values"]) );
  58.         $s = "INSERT INTO `". $data["table"]."`(". $rows .") VALUES(". $values .");";
  59. //      echo $s.'<br>'; return true;
  60.         $q = mysqli_query($conn, $s);
  61.         if( !$q ){
  62.             echo error_mysql( $conn );
  63.             return false;
  64.         }
  65.         return mysqli_insert_id($conn);
  66.        
  67.     }else if( $data["action"] == "delete" && !empty($data["id"]) ){
  68.        
  69.         return mysqli_query($conn, "DELETE FROM `". $data["table"] ."` WHERE id='". $data["id"] ."'");
  70.        
  71.     }else if( $data["action"] == "update" && !empty($data["table"]) && !empty($data["values"]) ){
  72.        
  73.         foreach(array_keys( $data["values"] ) as $v){
  74.             $t[] = "`".$v."` = '" . $data["values"][$v] . "'";     
  75.         }
  76.         $t = implode(", ", $t );
  77.         $s = "UPDATE `". $data["table"] ."` SET ". $t ." WHERE id = '". $data["id"] ."'";
  78.         echo $s; return false;
  79.         return mysqli_query($conn, $s);
  80.        
  81.     }else{
  82.         return false;  
  83.     }
  84. }
  85. // -->
  86. function register_user($data = null){ // registra al usuario
  87.     global $conn;
  88.     if( !is_array( $data ) || empty( $data ) ){ return false; }
  89.     $data = SecureData($data);
  90.     $privacidad = updateTable( array("table"=> "privacidad", "action" => "new", "values" => array("busqueda" =>"publico", "visible" => "publico") ) );
  91.     if( !$privacidad ){ return false; }
  92.     $ubicacion = updateTable( array("table"=> "ubicacion", "action" => "new", "values" => array("pais" =>0, "estado" => 0, "municipio" => 0) ) );
  93.     if( !$ubicacion){
  94.         updateTable( array("table"=> "privacidad", "id" => $privacidad, "action" => "delete" ) );
  95.     }
  96.     $tour = updateTable( array("table"=> "tour", "action" => "new", "values" => array("foto" =>0, "verificado" => 0, "emailverificado" => 0) ) );
  97.     if( !$tour){
  98.         updateTable( array("table"=> "privacidad", "id" => $privacidad, "action" => "delete" ) );
  99.         updateTable( array("table"=> "ubicacion", "id" => $ubicacion, "action" => "delete" ) );
  100.         return false;
  101.     }
  102.        
  103.     $premium = updateTable(
  104.         array("table"=> "premium", "action" => "new", "values" => array("mensajes" =>0, "fotografias" => 0, "eventos" => 0, "reputacion" =>0, "busqueda" =>0, "visitas" => 0) ) );
  105.     if( !$premium){
  106.         updateTable( array("table"=> "privacidad", "id" => $privacidad, "action" => "delete" ) );
  107.         updateTable( array("table"=> "ubicacion", "id" => $ubicacion, "action" => "delete" ) );
  108.         updateTable( array("table"=> "tour", "id" => $tour, "action" => "delete" ) );
  109.         return false;
  110.     }
  111.     $new = updateTable(array(
  112.                             "action" => "new",
  113.                             "table" => "usuarios",
  114.                             "values" => array(
  115.                                             "nick" => $data["nick"],
  116.                                             "email"  =>  $data["email"] ,
  117.                                             "password"  =>  $data["password"] ,
  118.                                             "usertype"  =>  $data["usertype"] ,
  119.                                             "avatar"  =>  0 ,
  120.                                             "status"  =>  1 ,
  121.                                             "online"  => time() ,
  122.                                             "privacidad"  =>  $privacidad ,
  123.                                             "ubicacion"  =>  $ubicacion ,
  124.                                             "tour"  =>  $tour ,
  125.                                             "premium" =>  $premium ,
  126.                                             "picpoints"  => 0
  127.                                         )
  128.                             )
  129.                         );
  130.         if( !$new ){
  131.             echo $error;
  132.             updateTable( array("table"=> "privacidad", "id" => $privacidad, "action" => "delete" ) );
  133.             updateTable( array("table"=> "ubicacion", "id" => $ubicacion, "action" => "delete" ) );
  134.             updateTable( array("table"=> "tour", "id" => $tour, "action" => "delete" ) );
  135.             updateTable( array("table"=> "premium", "id" => $premium, "action" => "delete" ) );
  136.             return false;
  137.         }
  138.         return mysqli_insert_id($conn);
  139.    
  140. }/*$s = "select * from usuarios
  141.         left join tour on usuarios.tour = tour.id
  142.         left join premium on usuarios.premium = premium.id
  143.         left join ubicacion on usuarios.ubicacion = ubicacion.id
  144.         left join privacidad on usuarios.privacidad = privacidad.id
  145.         where usuarios.id = 3";
  146. $q = mysqli_query($conn, $s);
  147.     $error = error_mysql( $conn );
  148.         if( $error ){
  149.             echo $error;
  150.             return false;
  151.         }
  152. $r = mysqli_fetch_object( $q );
  153. ar( $r );*/
  154. //---->
  155. $conn = mysqli_connect(SDB, UDB, PDB, DB);// conexion a la base de datos
  156. if (!$conn) {
  157.     printf("Conexi&oacute;n fallida: %s\n", mysqli_connect_error());
  158.     exit();
  159. }
  160. mysqli_set_charset($conn, "utf8");// Definimos que usaremos utf8 como codificacion
  161. $register = register_user(array('nick'=>'admin',  'email'=>'[email protected]',  'password'=>'asdasd',  'usertype'=>'user'));
  162. ar( $register );
  163. mysqli_close($conn);

aqui la estructura de las tablas que utilizo::

Código MySQL:
Ver original
  1. CREATE TABLE IF NOT EXISTS `premium` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `credito` float(6,2) DEFAULT '0.00',
  4.   `mensajes` int(11) DEFAULT NULL,
  5.   `fotografias` int(11) DEFAULT NULL,
  6.   `eventos` int(11) DEFAULT NULL,
  7.   `reputacion` int(11) DEFAULT NULL,
  8.   `busqueda` int(11) DEFAULT NULL,
  9.   `visitas` int(11) DEFAULT NULL,
  10.   PRIMARY KEY (`id`)
  11. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
  12.  
  13. -- --------------------------------------------------------
  14.  
  15. --
  16. -- Estructura de tabla para la tabla `privacidad`
  17. --
  18.  
  19. CREATE TABLE IF NOT EXISTS `privacidad` (
  20.   `busqueda` varchar(45) DEFAULT NULL,
  21.   `visible` varchar(45) DEFAULT NULL,
  22.   PRIMARY KEY (`id`)
  23. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
  24.  
  25. -- --------------------------------------------------------
  26.  
  27. --
  28. -- Estructura de tabla para la tabla `tour`
  29. --
  30.  
  31. CREATE TABLE IF NOT EXISTS `tour` (
  32.   `foto` tinyint(1) DEFAULT NULL,
  33.   `verificado` tinyint(1) DEFAULT NULL,
  34.   `emailverificado` tinyint(1) DEFAULT NULL,
  35.   PRIMARY KEY (`id`)
  36. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
  37.  
  38. -- --------------------------------------------------------
  39.  
  40. --
  41. -- Estructura de tabla para la tabla `ubicacion`
  42. --
  43.  
  44. CREATE TABLE IF NOT EXISTS `ubicacion` (
  45.   `id` int(11) NOT NULL AUTO_INCREMENT,
  46.   `pais` int(11) DEFAULT NULL,
  47.   `estado` int(11) DEFAULT NULL,
  48.   `municipio` int(11) DEFAULT NULL,
  49.   PRIMARY KEY (`id`)
  50. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
  51.  
  52. -- --------------------------------------------------------
  53.  
  54. --
  55. -- Estructura de tabla para la tabla `usuarios`
  56. --
  57.  
  58. CREATE TABLE IF NOT EXISTS `usuarios` (
  59.   `nick` varchar(100) DEFAULT NULL,
  60.   `email` varchar(320) DEFAULT NULL,
  61.   `password` varchar(300) DEFAULT NULL,
  62.   `usertype` varchar(45) DEFAULT NULL,
  63.   `status` tinyint(1) DEFAULT '1',
  64.   `online` int(20) DEFAULT NULL,
  65.   `ubicacion` int(11) NOT NULL,
  66.   `tour` bigint(20) NOT NULL,
  67.   `privacidad` bigint(20) NOT NULL,
  68.   `premium` int(11) NOT NULL,
  69.   `avatar` bigint(20) NOT NULL,
  70.   `picpoints` int(11) DEFAULT NULL,
  71.   PRIMARY KEY (`id`)
  72. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
[/CODE]
  #2 (permalink)  
Antiguo 26/02/2014, 13:01
Avatar de gnzsoloyo
Moderador criollo
 
Fecha de Ingreso: noviembre-2007
Ubicación: Actualmente en Buenos Aires (el enemigo ancestral)
Mensajes: 23.324
Antigüedad: 16 años, 4 meses
Puntos: 2658
Respuesta: "insert duplicado" dos entradas al ejecutar un script

Off Topic: El problema no es MySQL, sino PHP.

Movido a PHP
__________________
¿A quién le enseñan sus aciertos?, si yo aprendo de mis errores constantemente...
"El problema es la interfase silla-teclado." (Gillermo Luque)

Etiquetas: doble, inserción, 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 21:45.