...

View Full Version : Detecting if row value already exists



WebmasterLULZ
03-15-2008, 10:47 PM
So I am running the following command.

INSERT INTO alert (id, message)
VALUES ('$id', 'test')

So say if $id = "123" , it will incert a record of 123 into the ID box.

How do I basically say "if the value of $id already exist in the row of alert in the ID field, than echo "ID already exist in database"

StupidRalph
03-16-2008, 12:17 AM
If you just want it to not take the action of inserting into the DB you could use IGNORE.



INSERT IGNORE INTO alert (id, message)
VALUES ('$id', 'test')


This will insert the record if the id does not exist and ignore it if it does. Alternatively you could use REPLACE if you wanted to repace the current database value. My code assumes that ID is a primary or unique key.

WebmasterLULZ
03-16-2008, 01:20 AM
What I want to happen is if , say if they say ?id=123 , if 123 already is in the record of "ID", than echo something like "ID Already exist in table" or something of that. So what I want to happen is it will look for the ID that was given in the $_GET function (lets say 123) , and if 123 already exist, run echo something. thats all I wnat to do is have it hunt and search.

WebmasterLULZ
03-16-2008, 03:20 AM
Let me rephrase my question:

I want to acomplish this

IF 123 already excist in rowname "ID" under tablename "alert", than do nothing and just echo, else , do the query

Inigoesdr
03-16-2008, 03:46 AM
You would have to use another query to check the database beforehand.
$result = mysql_query('SELECT COUNT(*) FROM `table` WHERE `id` = 123');
$count = mysql_result($result, 0);
if($count == 1)
{
echo 'Row exists already';
}

InsaneRhino
03-17-2008, 02:44 AM
This may not help much but I often use an extended version of Inigoesdr's code, its not what you asked for, but I will post it in case somebody finds it useful:


$result = mysql_query('SELECT COUNT(*) FROM `table` WHERE `id` = 123');
$count = mysql_result($result, 0);
if($count == 1)
{
UPDATE alert SET (id, message) VALUES ('$id', 'test') WHERE xxx
}else{

INSERT INTO alert (id, message) VALUES ('$id', 'test')

}

Inigoesdr
03-17-2008, 04:27 AM
If you were going to update it anyway you should just use REPLACE INTO, so you only need one query.

InsaneRhino
03-17-2008, 12:09 PM
heheh thats why I love this forum. I love learning even when I'm the one trying to help :P



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum