Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
How to avoid inserting duplicate values into a database?

Below code inserts into database, but I don't want separate rows for example, have User ID with name alan and another row saying a different name, i want it to be userID and names associated in one

Can someone help?

What I have tried:

try{
	
$stmt = $conn->prepare('INSERT INTO favourites (nameID,UserID) VALUES (:nameID, :UserID);');
			$stmt->execute(array(
				':nameID' =>$_POST['nameID'],
				':UserID' =>$_POST['UserID']
				));
			$count = $stmt->rowCount();
			if($count > 0 )
			{
				echo "<span style='font-size:100%;color:red;'>❤️";
			}
			else {
				echo "unsuccessful";
			}
}
catch(PDOException $error)
{
	echo $error->getMessage();
}
?>
Posted
Updated 14-Feb-18 1:38am

1 solution

There are a few ways to achieve what you want ... the technique is often known as "upsert" (update or insert) or "merge". These articles discuss the various ways you can do this in MySQL:
How to INSERT If Row Does Not Exist (UPSERT) in MySQL[^]
3 ways to write UPSERT and MERGE queries in MySQL · Baron Schwartz's Blog[^]
and here are some worked examples: MySQL: Insert record if not exists in table[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900