Jump to content

Archived

This topic is now archived and is closed to further replies.

Nomax5

Bit embarrassing I need help update or delete

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?

Share this post


Link to post
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]

Share this post


Link to post
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 ::)

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

×

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.