Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Data from Just-Inserted Row (MySql and Node.js)

if I have a query like the following:

var queryString = "INSERT INTO pid SET title = '" + randomTitle + "', poc = '" + random + "';"
connection.query(queryString, function(err, rows, fields) {

...(do something here)
});

, is there a way I can retrieve information for the just-inserted row without performing a new query (in my particular case, I want the auto-generated primary key value).

For instance, can I use the construct with the "query" object (below) and then perhaps use one of the query.on callback to retrieve the information about the just-inserted row?:

var query = connection.query(queryString, function(err, rows, fields) {

    query.on('fields', function(fields) {
    ... get the field information?
    });

    query.on('result', function(row) {
    .. get the field information?
    });


});

If not via the query callbacks, is there another way? Thanks for any response!

like image 209
Tim Clotworthy Avatar asked Jan 07 '16 21:01

Tim Clotworthy


People also ask

How do I find the last inserted record?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.

CAN node JS interact with MySQL?

Once you have MySQL up and running on your computer, you can access it by using Node. js. To access a MySQL database with Node. js, you need a MySQL driver.


1 Answers

According to docs it is possilbe. Notice that callback function of insert query does not have rows and fields but only result parameter:

connection.query(queryString, function(err, result) {
    if (err) {
        // handle error
    }
    console.log(result.insertId); // prints inserted id
}

Your query is also vulnerable to sql injection. It should look like this:

var queryString = "INSERT INTO pid SET title = ?, poc = ?";
connection.query(queryString, [randomTitle, random], function(err, result) {
    // ...
}
like image 56
madox2 Avatar answered Nov 14 '22 03:11

madox2