Nomax5 Posted July 26, 2006 Share Posted July 26, 2006 I’ve been searching every where for this, I think there is something fundamental I don’t understandSuppose I have a table containing [b]name, fish, size[/b]And I have a form where visitors can enter the dataI only want one record per name, if the name already exists I want to Update the record/row And if it doesn’t then I want to insert a record. I don’t know how I should code itShould I try to insert and have it fail because name is unique, or do I try to update and catch some no rows updated message?What is an efficient method please? Quote Link to comment Share on other sites More sharing options...
zq29 Posted July 26, 2006 Share Posted July 26, 2006 You could try:[code]<?php$name = $_POST['name'];$check = mysql_result(mysql_query("SELECT COUNT(*) FROM `table` WHERE `name`='$name'"),0);if($check > 0) { //UPDATE} else { //INSERT}?>[/code] Quote Link to comment Share on other sites More sharing options...
obsidian Posted July 26, 2006 Share Posted July 26, 2006 [quote author=Nomax5 link=topic=101914.msg403796#msg403796 date=1153917319]What is an efficient method please?[/quote]imho, the most efficient method is to check to see whether the row already exists or not and query accordingly. for instance, if you have your user-entered values already in variables, you may try something like this:[code]<?php$q = mysql_query("SELECT COUNT(*) AS count FROM tableName where `name` = '$name'");$n = mysql_result($q, 0, 'count');if ($n == 0) $sql = "UPDATE tableName SET `fish` = '$fish', `size` = '$size' WHERE `name` = '$name'";elseif $sql = "INSERT INTO tableName VALUES ('$name', '$fish', '$size')";mysql_query($sql);?>[/code]hope this helps[b]**EDIT**[/b]DOH! SA, beat me to it ::) Quote Link to comment Share on other sites More sharing options...
Nomax5 Posted July 26, 2006 Author Share Posted July 26, 2006 Ahh I understand.... I'm just a little old fashioned with databases and am always concerned about accessing them needlessly. You know seeing as disks are slow and mechanical, and indexes my exist in memory …Thank both of you very much for your help. This really is one of my very favourite websites. PS PHP Freaks is in my Website Charts you can vote for it here http://www.votedtop.com/Web/PHP-Help-PHP-Freaks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.