Duplicate records in mysql

1

the registration from an html form to my database is a success but now I find the problem that I have left pending because I can not solve to send a message that the registration already exists, try some things but not I find ...

.php code to insert into the table

<?php session_start();
if(isset($_SESSION['Usuario'])){?>

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<head>   
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <link rel="stylesheet" href="css/estilo4.css" type="text/css" media="all">
 <title>Confirmación</title>  
</head>

<body>
 <div id=header>
  <img src="images/logocfe.png" width="200" height="100" alt="Logo CFE" />
  <table width="1339" class="barra" height="30" border="0" bgcolor="#336633">
         <td></td>
  </table>
 </div>
 <div>
  <?php     
   $direccion_ip=$_POST['direccion_ip']; 
   $mascara_de_subred=$_POST['mascara_de_subred'];
   $ocupada_por=$_POST['ocupada_por'];
   $nodo=$_POST['nodo'];
   $switch_panel=$_POST['switch_panel'];
   $idDpto=$_POST['idDpto'];
  ?>

  <div class="menu" id=registro>
    <center><h1>Datos de Registro dados de Alta</h1>

       Dirección IP: <?php echo $direccion_ip; ?><br>
       Máscara de Subred: <?php echo $mascara_de_subred; ?><br>
       Ocupada por: <?php echo $ocupada_por; ?><br>
       Nodo: <?php echo $nodo; ?><br>
       Switch/Panel: <?php echo $switch_panel; ?><br>
       Departamento: <?php echo $idDpto; ?><br>
    </center>
    </div>
    <?php

      $direccion_ip=$_POST['direccion_ip'];
      $mascara_de_subred=$_POST['mascara_de_subred'];
      $ocupada_por=$_POST['ocupada_por'];
      $nodo=$_POST['nodo'];
      $switch_panel=$_POST['switch_panel'];
      $idDpto=$_POST['idDpto'];

      include('libreria2.php');

      $insert = "INSERT INTO ips (direccion_ip, mascara_de_subred, ocupada_por, nodo, switch_panel, idDpto) VALUES ('$direccion_ip', '$mascara_de_subred', '$ocupada_por', '$nodo', '$switch_panel', '$idDpto')";
      conectar_bd($insert) ;


      echo "<center><br>Dirección IP dada de alta corectamente<br></center>";



    ?>
    </div>
    <center><a id="submit" href='altaip.php'>Registrar otra Dirección IP</a><br></center>
    <center><a id="submit" href='menu.php'>Volver al menú</a><br></center>
</body>  
</html> 
<?php
  }else{
   echo 'echo <script> window.location="index.php"; </script>';
  }
?>

Both "ip_address" and "node" declare them as unique, so as such, the duplicate record is not reflected in the database, but it does give me the success message on the page

Code of connection to the BD .php

   <?php

 function conectar_bd($query)
 {
 $DB_SERVER = "xxx.xxx.com";
 $DB_USER = "user";
 $DB_DATABASE = "xxx";
 $DB_PWD = "123";

 $conn=mysqli_connect($DB_SERVER, $DB_USER,$DB_PWD, $DB_DATABASE);
 /* check connection */
 if (mysqli_connect_errno())
 {
    printf("Connect failed: %s\n" , mysqli_connect_error());
    exit();
 }
 if ($result=mysqli_query($conn,$query))
   echo mysqli_connect_error();
 return $result;
 }

?>
    
asked by Jair Mejía López 03.04.2018 в 20:07
source

3 answers

1

You need to return the result of your query in the function "conecta_bd". If the INSERT was a success, you display the success message, otherwise, you display another message saying what the error was.

function conectar_bd($query)
 {
     $DB_SERVER = "serverdb.cfe.mx";
     $DB_USER = "jair";
     $DB_DATABASE = "dbIPs";
     $DB_PWD = "123";

     $conn=mysqli_connect($DB_SERVER, $DB_USER,$DB_PWD, $DB_DATABASE);
     /* check connection */
     if (mysqli_connect_errno())
     {
         printf("Connect failed: %s\n" , mysqli_connect_error());
         exit();
     }
     $result=mysqli_query($conn,$query);
     if ($result)
         return 'Success';
     } else {
         return 'Failure'
     }
}

You also have to change these lines:

 conectar_bd($insert) ;

 echo "<center><br>Dirección IP dada de alta corectamente<br></center>";

Because of this:

 $result = conectar_bd($insert) ;
 if ($result == 'Success') {
     echo "<center><br>Dirección IP dada de alta corectamente<br></center>";
 } else {
     echo "<center><br>Dirección IP dada ya existe<br></center>";
 }
    
answered by 03.04.2018 в 20:14
0

It is not a good idea to give the database a load of project logic, that creates additional complexity in the maintenance of the code. It is advisable to make a prior consultation (SELECT) asking if the IP address exists and if not, then do the INSERT.

Answering your question, modify this part:

conectar_bd($insert) ;
echo "<center><br>Dirección IP dada de alta corectamente<br></center>";

By:

if(conectar_bd($insert)) {
    echo "<center><br>Dirección IP dada de alta corectamente<br></center>";
} else {
    echo "<center><br>La direccion IP no ha podido ser insertada<br></center>";
}
    
answered by 03.04.2018 в 20:37
0

What you could do in my opinion before the insert is to check that previously there is no record in the database that you are going to insert example:

//datos del post
$nombre = $_POST["nombre"];
$email = $_POST["email"];
$fecha = date("Y-m-d"); 

//COMPROBACION
// Comprobamos si el usuario esta registrado

$nuevo_usuario=mysql_query("select nombre from $tabla where nombre='$nombre'");
if(mysql_num_rows($nuevo_usuario)>0)
{
echo "
<p class='avisos'>El nombre de usuario ya esta registrado</p>
<p class='avisos'><a href='javascript:history.go(-1)' class='clase1'>Volver atrás</a></p>
";
}
// ------------ Si no esta registrado el usuario continua el script
else
{
// ==============================================
// Comprobamos si el email esta registrado

$nuevo_email=mysql_query("select email from $tabla where email='$email'");
if(mysql_num_rows($nuevo_email)>0)
{
echo "
<p class='avisos'>La direccion de e-mail ya esta registrada</p>
<p class='avisos'><a href='javascript:history.go(-1)' class='clase1'>Volver atrás</a></p>
";
}
// ------------ Si no esta registrado el e-mail continua el script
else
{
$result = mysql_db_query("$base_datos","insert into $tabla (nombre,email,fecha) values ('$nombre','$email','$fecha')"); 

include('cierra_db.php');

// Confirmamos que el registro ha sido insertado con exito

echo "
<p class='avisos'>Registro insertado con exito</p>
<p class='avisos'><a href='javascript:history.go(-1)' class='clase1'>Volver atrás</a></p>
";
} 
// ==============================================
} 

It's a small clear example, there are many ways to do it and optimize the code always before an insert you should have a method or function that you are going to consult in your db if the data exists that you are going to insert in case of existing since you return a message from the existing record you could show the user a message

"Registro existen desea modificarlo ?"

If the record does not exist insert it and notify the user of the correct insert! luck !!

    
answered by 03.04.2018 в 20:58