Jump to content


Photo

Bit embarrassing I need help update or delete


  • Please log in to reply
3 replies to this topic

#1 Nomax5

Nomax5
  • Members
  • PipPipPip
  • Advanced Member
  • 62 posts
  • LocationYork England

Posted 26 July 2006 - 12:35 PM

I’ve been searching every where for this, I think there is something fundamental I don’t understand

Suppose I have a table containing name, fish, size
And I have a form where visitors can enter the data

I 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 it
Should 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?


#2 Kris

Kris
  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 26 July 2006 - 12:37 PM

You could try:
<?php
$name = $_POST['name'];
$check = mysql_result(mysql_query("SELECT COUNT(*) FROM `table` WHERE `name`='$name'"),0);
if($check > 0) {
    //UPDATE
} else {
    //INSERT
}
?>


#3 obsidian

obsidian
  • Staff Alumni
  • Advanced Member
  • 3,202 posts
  • LocationSeattle, WA

Posted 26 July 2006 - 12:40 PM

What is an efficient method please?


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:
<?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);
?>

hope this helps

**EDIT**
DOH! SA, beat me to it ::)
You can't win, you can't lose, you can't break even... you can't even get out of the game.

<?php
while (count($life->getQuestions()) > 0)
{   $life->study(); } ?>
  LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

#4 Nomax5

Nomax5
  • Members
  • PipPipPip
  • Advanced Member
  • 62 posts
  • LocationYork England

Posted 26 July 2006 - 12:51 PM

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....Help-PHP-Freaks





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users