check if entry exists before inserting duplicant entry?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
jameso
Forum Newbie
Posts: 7
Joined: Wed Mar 17, 2004 3:31 pm

check if entry exists before inserting duplicant entry?

Post by jameso »

Before adding a user to my MySQL database I want to check to make sure they don't exist already. I want to validate their ID, FirstName, and LastName before running the query to insert them into the database.
I can provide any code I'm working with if you want but this seems like a simple IF or maybe even a built-in feature of MySQL(?).

Any suggestions? It'd be nice to turn this into a function too, for later use.

Thanks in advance.
coreycollins
Forum Commoner
Posts: 67
Joined: Sun Feb 01, 2004 1:04 pm
Location: Michigan

Post by coreycollins »

The way I ususally do it is by checking the data against the database. I just do a SELECT with the user supplied information. I don't know if this is the best way though...
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post by tim »

this works for me and i like it:

Code: Select all

<?php
$sel = "SELECT username FROM table_name where username = '$username'";
$quer = mysql_query($sel);
$row = mysql_fetch_array($quer);
$final = $row["user"];

if ($final == "") {
$result = "INSERT INTO etc etc etc"; 
mysql_query($result);
echo "Thanks for signing up $username";
} else {
echo "the name, $username, has been taken";}

// something to that effect
?>
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

Also described here viewtopic.php?t=19442
jameso
Forum Newbie
Posts: 7
Joined: Wed Mar 17, 2004 3:31 pm

Post by jameso »

Thanks!
Post Reply