Error #1442 - Unable to Update Database Table

I recently set up a trigger to automatically calculate the total sum of numbers in the FinalMarks column every time a new record is inserted into the student_marks table.

Unfortunately, I encountered an error message when attempting to insert a new record into the table.

If you could please identify where my mistake is, I would greatly appreciate it.

Thank you,

Taha

-

CREATE DEFINER = `root`@`localhost` TRIGGER `insert_student` BEFORE INSERT ON `student_marks`
  FOR EACH
  ROW INSERT INTO student_marks( FinalMarks )
  VALUES (
  AssignmentMarks + QuizMarks + Hourly1 + Hourly2 + Hourly3 + ProjectMarks
  )
  

ERROR

  INSERT INTO `university`.`student_marks` (
  

StudentMarksId , StudentId , SemesterCourseId , AssignmentMarks , QuizMarks , Hourly1 , Hourly2 , Hourly3 , FinalMarks , Grades , ProjectMarks , GPA ) VALUES ( NULL , '1', '1', '10', '15', '20', '15', '10', '', '', '', '' )

-

#1442 - #1442 - Can't update table 'student_marks' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

Answer №1

Edit 1:

It's functioning properly for insertion, I would also like to trigger an update on FinalMarks whenever a Teacher updates any Field Marks. – Taha Kirmani

In addition to the BEFORE UPDATE trigger with the same SET logic,
Ensure that the trigger name and type are different.

For instance,:

DELIMITER //

CREATE DEFINER = `root`@`localhost` 
  TRIGGER `bu_student` BEFORE UPDATE ON `student_marks`
  FOR EACH ROW 
BEGIN
    SET NEW.FinalMarks = NEW.AssignmentMarks + NEW.QuizMarks
                       + NEW.Hourly1 + NEW.Hourly2 + NEW.Hourly3 
                       + NEW.ProjectMarks;
END;
//

DELIMITER ;

Original answer:

It appears that you want to assign a specific value to the field FinalMarks by summing up the inserted values. This can be achieved without executing another insert statement on the table.

Rather than using another insert statement, you can simply utilize the SET command within the trigger code to accomplish this task.

Modification:

CREATE DEFINER = `root`@`localhost` 
  TRIGGER `insert_student` BEFORE INSERT ON `student_marks`
  FOR EACH ROW 
    INSERT INTO student_marks( FinalMarks )
    VALUES (
      AssignmentMarks + QuizMarks + Hourly1 + Hourly2 + Hourly3 + ProjectMarks
    )

To achieve this:

CREATE DEFINER = `root`@`localhost` 
  TRIGGER `insert_student` BEFORE INSERT ON `student_marks`
  FOR EACH ROW 
    SET NEW.FinalMarks = NEW.AssignmentMarks + NEW.QuizMarks
                       + NEW.Hourly1 + NEW.Hourly2 + NEW.Hourly3 
                       + NEW.ProjectMarks;

Reference:
MySQL: CREATE TRIGGER Syntax
Take a look at one of the examples in the User Comments section on the linked page.

Answer №2

Had to manually write PHP code in order to resolve this issue.

Visit this forum thread for more information

Encountering a MySql error: Unable to update table in stored function or trigger due to prior usage by invoking statement

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any issues with this Ajax request?

I am currently working on an Ajax call that will submit a form and display different content based on the server's response: $('#applyForm').submit(function(){ var dataString = $(this).serialize(); $.ajax({ type: "POST", url: "php/c ...

When a link is clicked, submit a form and send it to several email addresses simultaneously

My form has been styled using the uniform jQuery plugin. Instead of using an input type submit for submitting the form, I have utilized a link and added some effects to it to prevent it from being formatted with uniform. <form> <ul> ...

PHP Issues with PHP While and ForEach loops causing unexpected outcomes

I am having trouble with my code logic. Currently, I am using a while loop to retrieve associated records for each meal_id. However, my foreach loop is not functioning as expected. My aim is to display the meal information first and then list the meal item ...

How should you handle a situation where a function is missing one argument?

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! function_exists('image_thumb')){ function image_thumb($courseBanner, $userId){ $CI =& get_instance(); $filename_ext ...

Having HWIOauthBundle version 0.3.*@dev installed on Symfony 2.3.4 resulted in encountering the common error message "No oauth code present in the request."

I'm hoping I haven't overlooked anything important. Following the instructions provided in this link, I have successfully installed HWIOauthBundle (along with FOSUserBundle): https://gist.github.com/danvbe/4476697 I copied code from the files t ...

I'm still searching for a proper solution on how to access JavaScript/jQuery functions within Colorbox

For my website, I am utilizing PHP, jQuery/JavaScript, Colorbox (a jQuery lightbox plugin), Smarty, and other tools. Currently, I am working on displaying data in a popup using the Colorbox plugin. However, I am facing an issue with calling a JavaScript fu ...

The "Submit Review" button is malfunctioning, as it inadvertently adds the product to the cart

I found this code snippet: <div class="buttons-set"><button type="submit" title="<?php echo $this->__('Submit Review') ?>" class="button"><span><span><?php echo $this->__('Submit Review') ?>< ...

can access the directory but unable to see the contents within

Hey there! I'm having some trouble displaying files from my folder directory. Whenever I try to use this code, it opens a new browser window but gives me a 404 error - object not found! Inside the folders, there are jpg images that I want to view thro ...

Search and extract JSON data in MySQL

Currently, I am inputting JSON objects into a MySQL Database and then executing queries on them. Within the database is a table structured as follows: subjects | ----------------------------------------------- ...

Utilizing the 24-hour clock for both the date and time

I have a meeting scheduled for Fri, 15 Jan 2016 15:14:10 +0800, and I would like to present the time as 2016-01-15 15:14:10. This is what I attempted: $test = 'Fri, 15 Jan 2016 15:14:10 +0800'; $t = date('Y-m-d G:i:s',strtotime($test) ...

Just need a quick example to kick start my project using fopen and curl for making requests

I am new to using web services and want to start extracting data from comindwork. I'm not sure where to begin, as I have never done this before. Someone recommended that I can retrieve data using either fopen or by sending a curl request, but I' ...

Guide to updating commas in fetchall to three columns using psycopg2

How can I fetch 3 columns from a table using fetchall and write them into a text file without commas? import psycopg2 import pandas as pd con = psycopg2.connect(database="dbname",user="postgres",password="pwd",host="local ...

Omitting row information from a database using php and jquery

Currently, I am in the process of developing an admin panel and I have encountered a challenge with implementing a confirm dialog before deleting certain data. To achieve this, I am utilizing a plugin known as confirmOn. Below is my current setup: HTML: ...

Using a single form, the rest of the form fields are restricted when uploading images with Ajax

I am facing a challenge with uploading an image using ajax. I have other fields in the form that require validation before submission is allowed. However, whenever I try to upload an image, all the fields in the form show errors. $('#my_thumbnail&apo ...

Dividing an array in Laravel according to the key value

Hey everyone, I'm currently working on a Laravel project where users need to submit data with files on a specific page. When the user clicks submit, multiple forms will be submitted at once. To achieve this, I am using formData to separate the files a ...

How to display specific MySQL results at the top of the query result

Currently, I am displaying the results ordered only by ID, but I require certain specific results to be displayed at the top. This is my current query: SELECT a.id,a.popis,a.datum,a.plocha,a.cena,a.podlazi,a.balkon,a.terasa,a.premiovy,a.aktivni,b.lokalit ...

PHP and Ajax: Steps to start a session once a login is successfully completed (remaining code functions normally)

Hello everyone, I am currently learning PHP and seeking assistance with a new project. I am in the process of creating a login page where I have implemented an onclick event on a button to validate the email and password ("pass") entered by the user (ensu ...

What is the reason for needing to use utf8_decode prior to inserting a UTF8 string into MySQL?

I encountered a perplexing issue that I was able to resolve by experimenting with different options. However, the solution doesn't quite make sense to me... Here's the scenario: I am receiving JSON data from Facebook encoded in UTF-8. My databas ...

What is the best way to send a database connection to a PHP method?

During my PHP class, I encountered a scenario where one of the methods required access to a database. How should I properly pass a database connection variable to this method? Should it be passed as a parameter through the constructor or directly in the ...

Pass the response from a MySql query executed in ExpressJS to a basic JavaScript file that is responsible for modifying the

I am currently utilizing ExpressJS as my server and MySql as my local database. However, I am facing a challenge in retrieving data from a specific table and sending the query result to either a vanilla JS file or directly editing HTML through NodeJS. Her ...