0

I cant quite think about how to do this with mysql and php. Basically I want to be able to submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.

$guid=$_POST['guid'];
$name=$_POST['name'];
//Username
$user="webhost";
//Password
$pass="*******";
//IP To Host
$ip="***********";
//Database
$db="dayz2";
//Table
$table="whitelist";

//Database Connection
$con=@mysql_connect("$ip", "$user", "$pass")
            or die(mysql_error());

//Select Database
$dbcon=@mysql_select_db($db, $con)
            or die(mysql_error());
$dupesql = "SELECT * FROM $table where (name = '$name' AND guid = '$guid')";

$duperaw = mysql_query($dupesql);

if (mysql_num_rows($duberaw) > 0) {
  echo "Entry Already Exists";
}
else {
//Query Data Into Whitelist Table
$sql="INSERT INTO $table (name, guid) VALUES ('$name', '$guid')";

//Submit Data into Whitelist Table
$result=@mysql_query($sql, $con) or die(mysql_error());
}
?>
Ryahn
  • 537
  • 7
  • 24
  • And what should it do if the record already exists? Nothing? Return an error? Increment a counter? Something else? Please include relevant information in your question. – Mark Byers Sep 16 '12 at 09:37
  • like what stuff do you want to check? – Akash KC Sep 16 '12 at 09:37
  • This might help http://stackoverflow.com/questions/7719039/php-duplicate-checking-before-insert –  Sep 16 '12 at 09:38
  • You should probably define unique constraints on your data, and just check for error `1062` ("duplicate entry") after you attempt the insert. – lanzz Sep 16 '12 at 09:40
  • I have updated my post to a php script I have tried to use but it doesnt display the error and stop the submittion – Ryahn Sep 16 '12 at 09:49

3 Answers3

1

You can do it in another way, instead of:

submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.

You can do:

INSERT data into a mysql database if not existed, else ignore them

Something like :

INSERT IGNORE INTO table
INSERT IGNORE INTO yourtablename
SET fieldname = 'blah'
,..
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
0

It depends what you are trying to do - what is the exact criteria for your query?

You have several options:

benedict_w
  • 3,543
  • 1
  • 32
  • 49
0

It depends how you want to handle case when the entry exists. I you want to throw some error then you can create table trigger for insert event and put some checks there, but it will be slow because every insert will do this check.

bary
  • 1,699
  • 2
  • 15
  • 24