How to avoid duplicate registration in a table in mysql [duplicate]

1

How do I stop repeating the card in the registry?

<?php

  $placa     =     $_POST['placa'];
  $cidade    =     $_POST['cidade'];
  $estado    =     $_POST['estado'];

$query  = "INSERT INTO veiculos (placa, cidade, estado) 
  VALUES('$placa','$cidade','$estado')";
  $result = mysqli_query($conn,$query); 
    
asked by anonymous 14.05.2018 / 05:01

2 answers

0

You can define in the database that the 'board' column is a UNIQUE type, which will not allow duplicate data, or you can create a SELECT on your page that verifies that the board already exists. If it exists it returns an error message, otherwise it performs the INSERT.

To do the SELECT you can: 1 - SELECT * FROM vehicles WHERE board = $ board 2 - SELECT board FROM vehicles WHERE board = $ board

Difference: in the first option you search all the vehicle information, so if you want more data to compare you can use this, if you do not need it, you can use the one below.

Your code looks like this:

$query = "SELECT * FROM veiculos WHERE placa = $placa"; 
$result = mysqli_query($conn,$query); //Faz select para consultar as placas
if(mysql_num_rows($result) > 0) //checa se a consulta teve alguma linha {
$query  = "INSERT INTO veiculos (placa, cidade, estado) 
  VALUES('$placa','$cidade','$estado')";
  $result = mysqli_query($conn,$query); 
} else {
echo "Erro";
}
    
14.05.2018 / 05:05
0

I ended up making some changes and it worked. Thank you for the LUZ that you gave me ....

 $query = "SELECT * FROM veiculos WHERE placa = '" . $_POST['placa'] . "'";
 $resulta = mysqli_query($conn, $query) or die (mysqli_error($conn));

 if(mysqli_num_rows($resulta) ==0 ){

 } else {


        echo "Cadastro não realizado";

 }
    
14.05.2018 / 15:32