php - Handle session while form submission

957

I have a web application where users fill the form and a unique id is generated like for example "SC001001". the code for generation is

$result = mysqli_query($con,"SELECT OA_NO FROM student where CUSTID='SC001'");
$x=0;
$num_rows = $result->num_rows;
if($num_rows==0){
    $var1="SC001001";
}
else{

while($row = mysqli_fetch_array($result))
  {
 $next[$x]=substr($row['OA_NO'],2);
 $x=$x+1;
  }

$arrlength=count($next);
$inc=max($next)+1;
$newvar= "SC00".$inc;
$var1=$newvar;
}

While saving it in the database the OA_NO is the primary key.

but when two users press the submit button at the same time i get the error message #1062. Duplicate entry present and the entry of the first request gets inserted...

my question is how shall i enter both the values with incrementing the second one.. PLEASE HELP!!

206

Answer

Solution:

If you find the maximum value while doing the insert, the value should always be unique. I added theLPAD function in case you wanted to keep the length of userID consistent:

INSERT INTO students (`OA_NO`, `userID`)
SELECT MAX(OA_NO) + 1, CONCAT('SC00', LPAD(MAX(OA_NO) + 1, 4,'0'))
FROM students
ON DUPLICATE KEY UPDATE 
    `OA_NO`  = VALUES(OA_NO) + 1, 
    `userID` = CONCAT('SC00', LPAD(VALUES(OA_NO) + 1, 4,'0'));
959

Answer

Solution:

You shouldn't generate a primary key that way.

If you want a sequential numbering, you should use an auto-incremented field as primary key (or as part of the primary key).

Hope it helps

People are also looking for solutions to the problem: html - Stop new PHP page poping up after a form button action

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.