Jump to content

MySQL Insert If Not Exists?


glassfish

Recommended Posts

The Script:

<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
    <input type="text" name="hashtags" />
    <input type="submit" name="submit" />

</form>
<?php

if(isset($_POST['submit'])){

    $hashtags = explode(", ", $_POST['hashtags']);

// Prints e.g.: Array ( [0] => #tag1 [1] => #tag2 [2] => #tag3 [3] => #tag4 )
    print_r($hashtags);
    
}

?>

This gets inserted into the input field:

#tag1, #tag2, #tag3, #tag4

I am looking to check if any of the hashtags inside the array already exist in the database, if it does not exists it should create the new ones in the table.

 

I know how to do this if all do not exists in the array and then it goes over to the MySQL query and inserts all of them.

 

My Question Is:

How to insert only the ones which do not exists out of the array, so the ones which do exists do not get inserted again into the table?

Link to comment
https://forums.phpfreaks.com/topic/291620-mysql-insert-if-not-exists/
Share on other sites

And we are assuming that despite your input field containing multiple data items that you are NOT storing that way in your db table.  You should have a hashtag table that has a user id field and a hashtag field and your table will then have multiple records for a user as in:

 

user     tag

john     #tag1

john     #tag2

john     #tag3

john     #tag4

Mary   #tag1

Mary   #tag2

By making the column "unique key", you are telling mysql that the column should not contain duplicates. So then mysql will not only reject the insert, it will throw an error.

That is why you add the ignore to the query, so that mysql ignores the error.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.