Error ER_NO_REFERENCED_ROW_2 occurred while attempting to use the function LAST_INSERT_ID

As a newcomer to Vue.js and Express, I've been trying to figure out how to transfer the GuestID from the Guest Table to the foreign key GuestID in my reservations table.

app.post('/create',(req,res,next)=>{
    var mysql = require('mysql')
    var connection = mysql.createConnection(config)
    var sql = "INSERT INTO `guest` SET ?"
    connection.query(sql,req.body,(err,results,fields)=>{
        connection.end()
        if(err){
            next(err)
        }else{
            res.json([true,results.insertId])
        }
    })
})


app.post('/book',(req,res,next)=>{
    var mysql = require('mysql')
    var connection = mysql.createConnection(config)
    var sql = "INSERT INTO `reservation` SET `GuestID`=LAST_INSERT_ID(),`RoomID`=?,`AdultCount`=?,`KidCount`=?,`CheckInDate`=?,`CheckOutDate`=?"
    var RoomID = req.body.RoomID;
    var AdultCount = req.body.AdultCount;
    var KidCount = req.body.KidCount;
    var CheckInDate = req.body.CheckInDate;
    var CheckOutDate = req.body.CheckOutDate;
    connection.query(sql,[RoomID,AdultCount,KidCount,CheckInDate,CheckOutDate],(err,results,fields)=>{
        connection.end()
        if(err){
            next(err)
        }else{
            res.json([true,results])
        }
    })
})

I'm encountering this specific Error message:

Error: ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (booking.reservation, CONSTRAINT reservation_ibfk_1 FOREIGN KEY (GuestID) REFERENCES guest (GuestID))

Answer №1

After a helpful tip from @Akina, I decided to explore ways to execute multiple queries on a single connection. I came across a post suggesting the use of `multipleStatements` in the connection setup, which led me to modify my code as follows:

app.post('/book',(req,res,next)=>{
    var mysql = require('mysql')
    var connection = mysql.createConnection(config)
    var sql = "INSERT INTO `guest` SET `FirstName`=?,`LastName`=?,`Email`=?,`ContactNumber`=?;SET @GuestID:=LAST_INSERT_ID();INSERT INTO `reservation` SET `GuestID`=@GuestID,`RoomID`=?,`AdultCount`=?,`KidCount`=?,`CheckInDate`=?,`CheckOutDate`=?"
    var FirstName = req.body.FirstName;
    var LastName = req.body.LastName;
    var Email = req.body.Email;
    var ContactNumber = req.body.ContactNumber;
    var RoomID = req.body.RoomID;
    var AdultCount = req.body.AdultCount;
    var KidCount = req.body.KidCount;
    var CheckInDate = req.body.CheckInDate;
    var CheckOutDate = req.body.CheckOutDate;
    connection.query(sql,[FirstName,LastName,Email,ContactNumber,RoomID,AdultCount,KidCount,CheckInDate,CheckOutDate],(err,results,fields)=>{
        connection.end()
        if(err){
            next(err)
        }else{
            res.json([true,results])
        }
    })
})

Although it may seem lengthy, this approach gets the job done. If anyone has suggestions for more efficient methods, I'm all ears!

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

Initially, my PDF file does not get selected, except in the Internet Explorer browser

I am currently facing an issue with selecting PDF files in Internet Explorer. The process works smoothly in Google Chrome, but I encounter a problem when trying to select PDFs in IE. Specifically, when I attempt to select a PDF for the first time in Inter ...

"Encountering a 'Cannot POST' error while working with

I am currently working on a form that dynamically adds user data to a table. You can view the final form layout here. However, when clicking on the "Use this account" button, an error message saying Cannot POST /like appears. The form is created using EJ ...

React.js onClick does not display the dropdown

Hello, I have a question regarding my navbar icon functionality. When I click on the icon, it is supposed to open a dropdown menu. However, although the div name changes when clicked, the CSS properties remain the same as the initial class. I am unsure w ...

A Guide to Listing Private JavaScript Class Properties

What is the best approach to iterate through private class fields? class Person { #isFoo = true; #isBar = false; constructor(first, last) { this.firstName = first; this.lastName = last; } enumerateSelf() { console.log(this); ...

Why doesn't Material-UI seem to understand the theme.spacing function?

Issue with Material-UI's theme.spacing function I've encountered a problem while using Material-UI's theme.spacing function in a React application. It seems that the spacing function is not being recognized. The Javascript error message st ...

When <li> elements are rendered via ajax, it is not possible to attach JavaScript Events to them

Hey there, I've got a drop down menu that's being shown using UL and LI tags. This is generated by a PHP script that echos out: '<li id='. $value .'>'.$value.'</li>' The JQuery function below works perf ...

Turn off images using Selenium Python

In order to speed up the process, I believe that disabling images, CSS, and JavaScript can help since Webdriver waits for the entire page to load before moving on. from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import Firef ...

Retrieve the height and width of all images within a specified directory using PHP

I'm currently working on an image directory in PHP, and I require the height and width of images in PHP to be used in HTML. I attempted to use JavaScript but it didn't provide the accurate values for the image's height and width. Can you sug ...

hosting a NextJS development server on the local network

When launching ReactJS with the npm start command, the development server is opened on both localhost:3000 and the network at 192.168.1.2:3000. Testing the app on various devices was a breeze thanks to this setup. Now that I've delved into learning N ...

What is the best way to display SVGs from an API response using next/image or the <img> tag in Next.js?

I have a collection of SVGs being returned from an API response, which I am fetching inside the useEffect. The response structure is as follows: {svg1: 'https://remoteserver.com/assests/svg1.svg', ...and so on} (These SVGs are not static assets ...

The call is not being answered by the server route (NodeJS + express)

I have encountered an issue while setting up a server using NodeJS and Express. When I attempt to make a get request to the basic route ('http://localhost:3000/'), the request seems to hang indefinitely. Despite thoroughly reviewing my code multi ...

The Zoom API is returning inaccurate dates when creating meetings

My app allows users to create and schedule meetings using Zoom, and here's how the process unfolds: The React app transmits data to my Express REST API The Express API forwards this data to the Zoom API The response received from the Zoom API is then ...

Error in Function Due to Undefined jQuery DataTable Parameters

In the jQuery datatable column, the below JavaScript code will display either a green checkmark button or a red X button: { data: "HasPayment", render: function (data, type, row, meta) { if (data) { return '<bu ...

Can you explain the purpose of having module.exports = function(app)?

Can you clarify the significance of the following codes? I would appreciate an explanation for all three lines. module.exports = function(app){ var x = express.router(); var y = express.router(); } I have tried researching these codes online, ...

Rendering ng-include before setting the source

Is there a way to prevent the ng-include directive from trying to render before a value on scope is set? Consider the following example: <ng-include src="'./lib/templates/' + $parent.currentEditable.editTemplate"></ng-include> It s ...

What causes the variable within the useEffect function to delay its value update?

const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> <input type="text" value={ ...

Can you provide the regular expression that will reject the character "?"

Can you help me verify that my form does not accept double quotes? Validators.pattern(/^(?!").*/g) The current solution is not functioning properly. I want to allow all characters except for double quotes. ...

Hough transformation in JavaScript with Node.js

Attempting to implement a 1-dimensional version of the Hough transform, focusing on optimizing for reduced dimensions based on minor properties. Included is the code and sample image with input and output visuals. Questioning what could be going wrong in ...

The variable "vue" is not properly defined within the instance, yet it is being called

I'm currently working on a Vue app and encountering an issue. The onScroll function is working correctly, but when I click the button component to trigger the sayHello function, I receive an error message. The error states: "Property or method &apo ...

Can dates in the form of a String array be transmitted from the server to the client?

Struggling to send a String array from the server side to the client using Nodejs and Pug. Encounter errors like "SyntaxError: expected expression, got '&'" or "SyntaxError: identifier starts immediately after numeric literal". Server runs o ...