Ruther Melchor Ruther Melchor - 1 month ago 14
MySQL Question

Prevent duplicate records from submitting; PHP & MySQL

Good day everyone, I'm trying to prevent duplicate records from being injected into a database of mine, I'm using the following code to prevent the data:




$con=mysqli_connect("localhost","root","","dbPos");
$first=trim($_POST['first']);
$last=trim($_POST['last']);
$emailaddress=trim($_POST['emailaddress']);

$queryF = "SELECT firstname FROM tbData WHERE firstname=='$first'";
$queryL = "SELECT lastname FROM tbData WHERE lastname=='$last";
$queryE = "SELECT emailaddress FROM tbData WHERE emailaddress=='$emailaddress'";

$resultF = mysqli_query($queryF);
$resultL = mysqli_query($queryL);
$resultE = mysqli_query($queryE);

if(mysqli_num_rows($con,$resultF) > 0 && mysqli_num_rows($con,$resultL) > 0 && mysqli_num_rows($con,$resultE) > 0)
{
header("Location: https://www.youtube.com"); //Just to check if it ignores the input.
}else{
mysqli_query($con,"INSERT INTO tbData VALUES (
'$first',
'$last',
'$emailaddress')");
header("Location: HOME.php");}
mysqli_close($con);





So I need it to check the first, and last name and the email address if there's a duplicate of it on the database, before it goes to the part of the code where it injects the data. Unfortunately, the code block where I check if there's a duplicate returns '0', so it proceeds on injecting the code in.

*Basically, the App should ignore the data inputted if it has the same first name, last name, and email address.

Any help would be highly appreciated!

Answer

Used the following logic with code below:

$resultFLE = mysqli_query($con,"SELECT * FROM tbData WHERE firstname='$first' AND lastname='$last' AND emailaddress='$emailaddress'");
$countFLE = mysqli_num_rows($resultFLE);
if($countFLE != null ){
     header("Location: HOME.php");
}else{
     mysqli_query($con,"INSERT INTO tbData VALUES ( 
         ...
     header("Location: HOME.php");
}

I tried to simplified things, and think of it again; tried to locate affected row first by comparing it to the inputted data one by one, counted it just to see if it hits my counter, and then routed the page to wherever I want to based on the result.