I have a data form that users enter their first name, last name, and email before users take a test. The data table has a Student_id
column that auto-increments every new user. My issue is trying to figure out how to get that Student_id
number after user submits the form, so I can store it in a variable on my Express app, eventually posting that number to another data table to keep track of current user.
I've tried the following with no success (most likely doing it wrong):
SCOPE_IDENTITY()
LAST_INSERT_ID
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/user-info', (req, res) => {
var first_name = req.body.first_name;
var last_name = req.body.last_name;
var email = req.body.email;
var sql = `INSERT INTO Govt_profiles (First_Name, Last_Name, Email)
SELECT ?, ?, ?
WHERE NOT EXISTS (SELECT 1 FROM Govt_profiles WHERE Email = ?)`;
pool.query(sql, [first_name, last_name, email, email], (err, data) => {
if (err) throw err;
});
res.redirect('/questions');
});
I'm able to post my data without issues, I'm just not able to figure out how to get that Student_id number.
I've tried the following with no success (most likely doing it wrong): SCOPE_IDENTITY()
and LAST_INSERT_ID
Ok I finally figured it out after moving on and returning to this issue. Thanks for everyone's help, here was my solution in my case.
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/user-info', (req, res) => {
var first_name = req.body.first_name;
var last_name = req.body.last_name;
var email = req.body.email;
var sql = `INSERT INTO Govt_profiles (First_Name, Last_Name, Email)
SELECT ?, ?, ?
WHERE NOT EXISTS (SELECT 1 FROM Govt_profiles WHERE Email = ?);
SELECT LAST_INSERT_ID()`;
pool.query(sql, [first_name, last_name, email, email], (err, data) => {
if (err) throw err;
})
.then(rows => {
console.log(rows[0].insertId);//<-----here's the freaking last insertId 😆!!!!!!
})
.catch(err => {
console.log(err);
})
});