Verify if record not exist


#1
$sql_v="select * from table WHERE id=id";
$result_v=mysqli_query($segjar,$sql_v);
while($row_v=mysqli_fetch_assoc($result_v)){
	if(mysqli_num_rows($resultado_v)==0){

$sql=“Insert into table …”;
}

Is not working

I also try

$sql_v="select * from table WHERE id=id";
$result_v=mysqli_query($segjar,$sql_v);
while($row_v=mysqli_fetch_assoc($result_v)){
	if(mysqli_num_rows($resultado_v)>0){

echo " record already exist";
}else{

echo " not exist";
$sql=“Insert into table …”;
}

Print exist records but else condition not do anything


#2

sorry

wrong code

should be

$sql_v="select * from table WHERE id=id";
$result_v=mysqli_query($segjar,$sql_v);

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

$sql=“Insert into table …”;
}


#3

And what are you trying to prevent a duplicate of? There are two better ways to handle this, depending on what you are trying to prevent.

  1. You create a composite key and mark it as unique. That prevents duplicate records from being inserted in the first place. This is the route you would want if you are trying to prevent users from having duplicate usernames.

  2. You do an upsert. It works as an insert if a record doesn’t exist, and an update if it does.


#4

Thank you for your help.
The composite primary key I already have.
The upsert.
I never listen nothing like that.
Could You Please give me one example


#5

If you are trying to prevent duplicates, just set a unique key on the field.

How about telling us about the real problem you are trying to solve instead of your attempt at solving it.


#6

I have solve it.
I just prevent duplicate records when i import data.
I only ask how to do it in other way with upsert


#7