user1046800
user1046800

Reputation: 1

php = insert working but want to check if in db already based on one field

Have a working system where I am posting news articles. I sometimes add the same one twice and want to avoid this. So how can I alter my insert statement to first check for a match on the field named 'title' to see if it is equal to the title I have in the record I am trying to submit?

Here is php code I use, as it was done for me since I am a PHP novice but I do not know how to check for the title=title and then not add it if it finds it or to add it if it doesnt find a match:

$result = mysql_query("
insert into news (
     catalogid,
     title,
     intro,
     content,
     viewnum,
     adddate,
     rating,
     ratenum,
     source,
     sourceurl,
     isdisplay,
     isfeature,
     subip,
     vsent,
     timesubmitted) 
values             
     ('1',
     '$title',
     '$intro',
     '$content',
     '0',
     '$subdate',
     '$source',
     '$icheck',
     'N/A',
     '$sourceurl',
     '$isapp',
     '0',
     '127.0.0.1',
     '0',
     '$tsdate')"
); 

Thank you!

Upvotes: 0

Views: 108

Answers (4)

xobicvap
xobicvap

Reputation: 302

You can't do this with a single INSERT statement, at least not directly. If you set the title field in your database table to UNIQUE, you can prevent MySQL from inserting a record with a duplicate title. You will need to detect if the mysql_query function returns FALSE; if it does, you know a duplicate record was inserted and you can handle this however you see fit.

Upvotes: -1

Rupesh Pawar
Rupesh Pawar

Reputation: 1917

$result = mysql_query("SELECT * FROM news WHERE `title`=$title");
if (!$result)
{
   // your code INSERT
   $result = mysql_query("
insert into news (
     catalogid,
     title,
     intro,
     content,
     viewnum,
     adddate,
     rating,
     ratenum,
     source,
     sourceurl,
     isdisplay,
     isfeature,
     subip,
     vsent,
     timesubmitted) 
values             
     ('1',
     '$title',
     '$intro',
     '$content',
     '0',
     '$subdate',
     '$source',
     '$icheck',
     'N/A',
     '$sourceurl',
     '$isapp',
     '0',
     '127.0.0.1',
     '0',
     '$tsdate')"
); 

}

Upvotes: -1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

You can run a check query before inserting , like:

$sql = mysql_query("SELECT catalogid from news WHERE title='".$yourTitle."'");
 if(mysql_num_rows($sql) < 1) {
     //add your insert query here
 }

Hope that helps

Upvotes: 1

user229044
user229044

Reputation: 239432

There are database-specific tricks like on duplicate key update, but typically you simply test for the existence of a record with the same key via a select. If the record exists, you update it with the new data, otherwise you insert a new record.

Upvotes: 2

Related Questions