How to avoid duplication of record in a table in mysql

Asked

Viewed 1,371 times

1

How do I not let repeat the plate in the register?

<?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); 

2 answers

0

I ended up making some changes and it worked. thanks for the LIGHT that Voce 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";

 }

-1

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

To do SELECT you can: 1 - SELECT * FROM vehicles WHERE plate = $plate 2 - SELECT plate from vehicles WHERE plate = $plate

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

Your code would look 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";
}
  • how would this select?

  • @Diogocarvalho added in the reply

  • this error appears. Warning: mysqli_num_rows() expects Parameter 1 to be mysqli_result, Boolean Given in

  • Make a test to see what it is returning. Apparently it returns false, IE, did not work your query. Replace > 0 with == false and invert what it would do (if it appears false it gives an error echo, otherwise it does the other query.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.