Reputation: 723
We have a table vehicle and a simple php form. Before inserting data I do check if the vehicle registration number exist but some client pc could enter duplicate entries. Below is the code snippet. What else could be causing this ?
$vehicleRegistrationNumber=$_POST['vehicleRegistrationNumber'];
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."'";
$result1 = mysqli_query($link,$selectQuery1);
$row1 = mysqli_fetch_array($result1, MYSQL_ASSOC);
$n1 = mysqli_num_rows($result1);
if($n1 > 0) {
$status="<span class=\"statusFailed\">: Vehicle ".$vehicleRegistrationNumber." Already Exist.</span>";
}
else {
//insert codes
}
Upvotes: 0
Views: 1367
Reputation: 5055
The best way is to handle it on the SQL side. Just define the field as UNIQUE INDEX.
Now when trying to insert a duplicate index an error will be thrown and you can catch it like this:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
Like this you can avoid the select query before every insert query. Just handle the error as you want.
Upvotes: 1
Reputation: 29492
First of all your code is vulnerable to SQL injection. This check can be bypassed by submitting something like XYZ0001' AND 1='0
or even more malicious values. To prevent this, use prepared statements and param binding instead of string concatenation.
Other possibility is simply user mistake, for example trailing space ("XYZ001" != "XYZ0001 "
) that is hard to spot on the first glance ad records in DB. Before checking its existence in DB you should check with PHP if submitted value includes only allowed chars and is free from common mistakes.
Upvotes: 1
Reputation: 37243
try this with group by
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."' GROUP BY vehicleRegistrationNumber";
Upvotes: 1