Pablo Cacho
Pablo Cacho

Reputation: 41

double inserting in mysql

Well, I have a form on html that makes an ajax call to a php function that inserts the values from the form into my database. So, there's no problem, until I get double row insert, i get the right row, and another empty row.

My js code

'use strict';

$.validator.addMethod("lettersonly", function(value, element) {
    return this.optional(element) || /^[a-z\s\ñ\Ñ]+$/i.test(value);
}, "Solo letras por favor");

$("#enviarEditar").click(function(){


var fiscales;
var fiscales2;
var personaContacto;
var email;
var pass;

 //VALIDACION DEL FORMULARIO EDITAR
           $('#formu').validate({

                        rules: {


                        fiscales:{
                                required:true
                        },
                        fiscales2:{
                            required:false
                        },
                       personaContacto:{
                            required: true
                        },
                        email:{
                            required:true,
                            minlength:4,
                            email:true,
                        },
                        pass:{
                          required:true,
                          minlength:5
                        },
                          },
                        messages: {
                              email: {
                                      remote: "Este correo ya esta en uso."
                                      }
                            },
        submitHandler: function() {







          fiscales = $('#fiscales').val();
           fiscales2 = $('#fiscales2').val();
           personaContacto = $('#personaContacto').val();
           email = $('#email').val();
           pass = $("#pass").val();



           $.ajax({
               type: 'POST',
               dataType: 'json',
               url: 'php/registro_admin.php',

               data: {
                   fiscales: fiscales,
                   fiscales2: fiscales2,
                   personaContacto:personaContacto,
                   email: email,
                   pass:pass


               },
               error: function(xhr, status, error) {


                    $.growl({

                  icon: "glyphicon glyphicon-ok",
                  message: "Administrador registrado correctamente!"

                },{
                  type: "success"
                });

               },
               success: function(data) {
                  var $mitabla =  $("#miTabla").dataTable( { bRetrieve : true } );
                  $mitabla.fnDraw();




                 if(data[0].estado==0){

                 $.growl({

                  icon: "glyphicon glyphicon-ok",
                  message: "Administrador registrado correctamente"

                },{
                  type: "success"
                });
               }else{

                 $.growl({

                  icon: "glyphicon glyphicon-ok",
                  message: "Administrador registrado correctamente!"

                },{
                  type: "success"
                });
               }

               },
               complete: {


               }
           });




        }

   });
  //FIN VALIDACION FORMULARIO EDITAR



});
//FIN CLICK

And my php file:

<?php
header('Access-Control-Allow-Origin: *');
/* Database connection information */
include("mysql.php" );

function fatal_error($sErrorMessage = '') {
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
    die($sErrorMessage);
}
/*
 * MySQL connection
 */
if (!$gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password'])) {
    fatal_error('Could not open connection to server');
}
if (!mysql_select_db($gaSql['db'], $gaSql['link'])) {
    fatal_error('Could not select database ');
}
mysql_query('SET names utf8');
/*
 * SQL queries
 * Get data to display
 */

$fiscales = $_GET["fiscales"];
$fiscales2 = $_GET["fiscales2"];
$personaContacto = $_GET["personaContacto"];
$email = $_GET["email"];
$pass = $_GET["pass"];




$query1= " INSERT INTO admin (datos_fiscales, datos_fiscales2, persona_contacto, email) VALUES ('".$fiscales."','".$fiscales2."','".$personaContacto."','".$email."')"; 
 log($query1);
echo $query1;


$query_res1 = mysql_query($query1);
if($query_res1){

$sql = "SELECT id_admin
        FROM admin
        where persona_contacto='".$personaContacto."'";

$res = mysql_query($sql);
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
$id_nuevo=$row['id_admin'];
}
}
//echo "idenuevo =>  $id_nuevo";
for ($i=0;$i<count($personaContacto);$i++)    
{     
//echo "<br> CLinicaid " . $i . ": " . $clinicas[$i];   
$query2 = "insert into usuario (nombre_usuario,password,tipo,cl_cliente,cl_editor,cl_medio,cl_admin) values( 
             '". $personaContacto . "', 
            '" . $pass . "',
            'admin',null,null,null,
            ".$id_nuevo.")" ;
//echo"$query1";
            $query_res2 = mysql_query($query2);
            echo $query2;
} 


if (!$query_res1||!$res||!$query_res2) {
   // $mensaje  = 'Error en la consulta de inserts: ' . mysql_error() . "\n";
   // $estado = mysql_errno();
    if (mysql_errno() == 1062) {
        $mensaje = "Imposible añadir el admin, id admin ya existe";
        $estado = mysql_errno();
    } else {
        $mensaje = 'Error en la consulta: ' . mysql_error() ;
        $estado = mysql_errno();
    }
}
else
{
    $mensaje = "Insercion correcta";
    $estado = 0;
}
$resultado = array();
 $resultado[] = array(
      'mensaje' => $mensaje,
      'estado' => $estado
   );
echo json_encode($resultado);
?>

I only have that issue with the first insert, cause in the second insert in table usuario everything goes fine.

Thank you so much

Regards

Upvotes: 0

Views: 1141

Answers (2)

Pablo Cacho
Pablo Cacho

Reputation: 41

Ok, i found the answer, It's not the good one, but it works. I have to do a delete where the id is empty after doing the inserts and it works.

Thanks everybody for helping me

Upvotes: 0

Brainfeeder
Brainfeeder

Reputation: 2632

You did not prevent the default form submit handler. It first fires the ajax submit and after that the form will submit as it is the default behaviour.

$("#enviarEditar").click(function(e) {
    e.preventDefault();

    // DO YOUR AJAX AND OTHER STUFF BELOWWW

});

Upvotes: 1

Related Questions