Jump to content

[SOLVED] Checking for duplicates in database on form submit


atl_andy

Recommended Posts

I had the idea to use the following to check for duplicate value when a form is submitted to a database:

 

elseif ($result == $_POST['serialnumber']) {
         $db_handle = pg_connect('dbname=test2 user=andy password=da4531');
         $query = 'SELECT serialnumber FROM system';
         $result = pg_query($query);
         pg_close($db_handle);
       echo "<h2><b>Duplicate serial number!  Go back, change serial number and submit form again.<b></h2><br />";
   }

 

I can't figure out how to get $_POST['serialnumber'] to check against each record of $result.  Any ideas?  All values of 'serialnumber' need to be unique.

<?php
// checks if the serialnumber is in use
if (!get_magic_quotes_gpc()) {
$_POST['serialnumber'] = addslashes($_POST['serialnumber']);
}
$serialcheckcheck = $_POST['serialnumber'];
$check = mysql_query("SELECT serialnumber FROM systems WHERE serialnumber = '$serialcheck'") 
or die(mysql_error());
$check2 = mysql_num_rows($check);

//if the serial exists it gives an error
if ($check2 != 0) {
die('Sorry, the serial number '.$_POST['serialnumber'].' is already in use.');
}
?>

I'm not sure where your coming from with the elseif but you would simply check the posted value in your query, something like....

 

<?php

 $sql = "SELECT serialnumber FROM system WHERE serialnumber = '{$_POST['serialnumber']}";
 if ($result = pg_query($sql)) {
   if (pg_num_rows($result)) {
     // you have a duplicate.
   } else {
     // No duplicate, good to do insert.
   }
 }

?>

It is going past the validation and sending the data to the table.    Should the pg_connect, query, pg_close be inside the if statement?  The syntax I used is:

 

   // Serial number validation
  $db_handle = pg_connect('dbname=test2 user=andy password=da4531');
   $sql = "SELECT serialnumber FROM system WHERE serialnumber = {$_POST['serialnumber']}";

   if ($result = pg_query($sql)) {
      if (pg_num_rows($result)) {
      echo "<h2><b>Duplicate serial number!  Go back, change serial number and submit form again.<b></h2><br />";
      }
      pg_close($db_handle);
   } else ...

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.