mac007 Posted February 7, 2009 Share Posted February 7, 2009 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 Link to comment https://forums.phpfreaks.com/topic/144182-how-to-check-first-if-value-already-in-a-column-if-so-not-insert-else-insert/ Share on other sites More sharing options...
gevans Posted February 7, 2009 Share Posted February 7, 2009 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()); } ?> Link to comment https://forums.phpfreaks.com/topic/144182-how-to-check-first-if-value-already-in-a-column-if-so-not-insert-else-insert/#findComment-756736 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.