0

We are developing an application for our college and in the fees module we need to check whether the student record is already present. If the student record does not exist we need to insert the record else we need to update the record.The code i have used is listed below:

if (isset($_POST['submit'])) {

  for($i=0; $i<count($_POST['mca_1_autogen_id']); ++$i){
   $sql=mysqli_query($conn,"UPDATE `fees_mca_1` set `Fees_paid`='{$_POST['Fp'][$i]}' where Register_number='{{$_POST['Regno'][$i]}'");
}
header("Location:mca1_fees_report.php");
 if(mysqli_affected_rows($conn) == 0){
 for($i=0; $i<count($_POST['mca_1_autogen_id']); ++$i){
   $sql=mysqli_query($conn,"INSERT INTO `fees_mca_1`(`Register_number`,`Student_name`,`Total_fees`,`Fees_paid`) VALUES ('{$_POST['Regno'][$i]}','{$_POST['Sname'][$i]}','{$_POST['Fees'][$i]}','{$_POST['Fp'][$i]}')") or die("Error: ".mysqli_error($dbc));
}}
header("Location:mca1_fees_report.php");
echo "Record Added Sucessfully";
 }

I have also tried this but no avail

if (isset($_POST['submit'])) {

for($i=0; $i<count($_POST['mca_1_autogen_id']); ++$i){
   $sql=mysqli_query($conn,"INSERT INTO `fees_mca_1`(`Register_number`,`Student_name`,`Total_fees`,`Fees_paid`) VALUES ('{$_POST['Regno'][$i]}','{$_POST['Sname'][$i]}','{$_POST['Fees'][$i]}','{$_POST['Fp'][$i]}') ON DUPLICATE KEY UPDATE `Fees_paid` = VALUES({$_POST['Fp'][$i]})");
}
header("Location:mca1_fees_report.php");
echo "Record Added Sucessfully";
  }
1
  • did you check ON DUPLICATE KEY in mysql? Commented Feb 2, 2018 at 4:07

3 Answers 3

2

You should use this instead:

INSERT INTO t1 (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

UPDATE t1 SET c=c+1 WHERE a=1;

It will check if the record is duplicated, then it will update it

Here is the Official Link to Sql Query .

Also please check ON DUPLICATE KEY

Sign up to request clarification or add additional context in comments.

Comments

0

You should use like this:

INSERT INTO table(column_list)  VALUES(value_list) ON DUPLICATE KEY UPDATE column_1 = new_value_1, column_2 = new_value_2, …;

Comments

0

You should try this

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.