Jump to content

how to check first if value already in a column, if so, not insert, else insert


mac007

Recommended Posts

Hi, all:

 

I have a simple table with columns like...

 

id,  accountid,  year

 

Let's say somebody may want to insert year "2009". I need to first check whether this "2009" year exists in the "year" column. If it exists then echo something like "year already present", and if it's not in column then go ahead and insert it. However, how would I check first that the value exists, and then use either the insert query based on whether the value exists?

 

Any help appreciated.

 

Thanks

Hi, all:

 

I have a simple table with columns like...

 

id,  accountid,  year

 

Let's say somebody may want to insert year "2009". I need to first check whether this "2009" year exists in the "year" column. If it exists then echo something like "year already present", and if it's not in column then go ahead and insert it. However, how would I check first that the value exists, and then use either the insert query based on whether the value exists?

 

Any help appreciated.

 

Thanks

 

You've just written the description of the code, you could've given it a try before asking!

 

<?php
//db connection ommited
$year = 2009;
$query = "SELECT `id` FROM `the_table` WHERE `year`=$year";
$result = mysql_query($query) or die("MySQL Error: ".mysql_error());
if(!mysql_num_rows($result)){
$query = "INERT INTO `the_table` (`id`, `accountid`, `year`) VALUES (YOUR VALUES)";
$result = mysql_query($query) or die("MySQL Error: ".mysql_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.