user866339
user866339

Reputation: 439

Insert if not exist php

I have the code

mysql_query("INSERT INTO authors (author) VALUES ('$rec_fic_author') WHERE NOT EXISTS (SELECT * FROM authors WHERE author='$rec_fic_author')") or die("cannot insert author");

Where authors is the table containing authorID (pk), and author $rec_fic_author is a _POST variable

I'm trying to make it so that when a person is adding an author, the code checks the database for anyone with the same name (under the author column). If not, then add the entry I have author as TEXT, and for some reason, I can't make it unique in phpMyAdmin. I looked into REPLACE and INSERT .. ON DUPLICATE KEY UPDATE, but as I understand they both need the value in question to be a unique/PK value. This is not the case here.

Help?

Upvotes: 0

Views: 1556

Answers (2)

Devart
Devart

Reputation: 121902

I'd suggest you to operate with PK or with UK (as wonk0 suggested), then you could use INSERT statement with INGNORE clause.

INSERT Syntax

Upvotes: 1

Imran Khan
Imran Khan

Reputation: 2401

This is a good query and NOT EXISTS is typically quite fast if you have good indexes. But i am wondering why this is not working!

I think this can be useful for your concern... LINK, Check it.

Upvotes: 0

Related Questions