简体   繁体   中英

How to get auto-incremented value when I app.post in ExpressJS app?

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

您必须选择最后一个插入 ID,例如

SELECT LAST_INSERT_ID()

If you're using the node module mysql you should be able to use results.insertId .

From Getting the id of an inserted row :

If you are inserting a row into a table with an auto increment primary key, you can retrieve the insert id like this:

connection.query('INSERT INTO posts SET ?', {title: 'test'}, function (error, results, fields) {
  if (error) throw error;
  console.log(results.insertId);
});

In sql you configure the field as auto incremented, no need to insert that filed value. On each insertion it will automatically take incremented value. Normally for primary key we configure AUTO_INCREMENT during table creation.

CREATE TABLE <tablename>(
id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (id));

Then we set a minimum level from which the value should start as this

ALTER TABLE <table name> AUTO_INCREMENT=9000;

so you can do the insert query as below

INSERT INTO <tablename>(FirstName,LastName)
VALUES ('Foo','Bar');

I believe that your problem is not with the query. It is with how Node.js works. It doesn't appear that you are waiting for the information to be returned from the post. Try running it using a promise or an async/await function.

http://www.acuriousanimal.com/2018/02/15/express-async-middleware.html

app.post('/user-info', async (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 = ?)`;

await pool.query(sql, [first_name, last_name, email, email], (err, data) => {
    if (err) throw err;
});

// await getIdSQL = `SELECT LAST_INSERT_ID()`
// if successful - send result 
// if failure - send error

});

On the client side, use the fetch API or AJAX to capture the message and redirect on success.

Either the pool is created with the default promise implementation ( require('mariadb'); ) then use

try {
   const res = await pool.query(sql, [first_name, last_name, email, email]);
   return res.insertId;
} catch(err) {
    //do something with error;
}

or if pool use callback implementation ( require('mariadb/callback'); ) then use

pool.query(sql, [first_name, last_name, email, email], (err, data) => {
    if (err) throw err;
    //do something with `data.insertId`
});

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);
})

});

Another way but not the best.

By knowing that Student_id is auto_increment value, you can use this sentence:

 SELECT `Student_id` FROM `Govt_profiles` WHERE Student_id=(SELECT MAX(Student_id) FROM `Govt_profiles`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM