Jump to content

check duplicates in database before posting form detail.


Recommended Posts

I use below code to post detail to MySQL database. how do I check duplicate of LastName already exist on the database and if exist then show an error message to user saying that LastName already exist, if not then proceed with code below to post content to MySQL.

 

<div>

<!-- MySQL create-->

<?php

$con = mysql_connect("localhost","forum","123456");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

 

mysql_select_db("forum", $con);

 

$sql="INSERT INTO forum (FirstName, LastName, Number)

VALUES

('$_POST[firstname]','$_POST[LastName]','$_POST[number]')";

 

if (!mysql_query($sql,$con))

  {

  die('Error: ' . mysql_error());

  }

echo "<div> Info posted to Data base.</div>";

 

mysql_close($con)

?>

 

</div>

 

 

EDIT: before you use this, what are you trying to accomplish? There may be a better way.

 

I think this should work. It's been a while since I've used mysql_result(), so syntax may be off though . . . Someone will correct me if I'm wrong, LOL.

$query = "SELECT COUNT(`LastName`) WHERE `LastName` = mysql_real_escape_string($_POST['LastName']";
$result = mysql_query($query);
if( mysql_result($result) > 0 ) {
     // name exists, so do something
} else {
     // name doesn't exits, so do something different.
}

Well my index.php have following like below

 

<form action="check.php" method="post">

Nick name: <input type="text" name="firstname" />

Last Name: <input type="text" name="lastname" />

Uniq ID: <input type="text" name="numer"  />

<input type="submit" value="Submit">

</form>

When user press submit it take them to check.php

 

which contain above mentioned php code (uses to post info to MySQL database)

 

I want to add ether on index.php or check.php, php code which checks whether user already exist and if so gives an error message.

 

Archived

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

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