Jump to content

Bit embarrassing I need help update or delete


Nomax5

Recommended Posts

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

Suppose I have a table containing [b]name, fish, size[/b]
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?
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

[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 ::)
Link to comment
Share on other sites

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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.