Jump to content

MySQL Insert If Not Exists?


glassfish
Go to solution Solved by Ch0cu3r,

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?

Edited by glassfish
Link to comment
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

Link to comment
Share on other sites

Thanks a lot! It works.

 

I am glad it works so great!

 

So basically, does SQL take over the checking if there is an "entry" already existing?

 

Before inserting I only check for the existing number of rows with "mysqli_num_rows()".

Edited by glassfish
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.