Good day,
I am willing to retrieve the id value of a freshly inserted row in Mysql.
I know there is mysqli_insert_id function, but:
I can't specify the table
Maybe there would be a risk of retrieving the wrong id, if a query is made in the meanwhile.
I am using node.js MySQL
I don't want to take the risk to query the highest id since there are a lot of queries, it could give me the wrong one...
(My id column is on auto-increment)
https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
describes the solution perfectly well:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result, fields) {
if (err) throw err;
console.log(result.insertId);
});
var table_data = {title: 'test'};
connection_db.query('INSERT INTO tablename SET ?', table_data , function(err, result, fields) {
if (err) {
// handle error
}else{
// Your row is inserted you can view
console.log(result.insertId);
}
});
You can also view by visiting this link https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
I think you misunderstood the use of mysqli_insert_id() method. This method must be executed immediately after the insert statement to obtain the last inserted id. if you do it my MySQL directly
INSERT INTO(a,b)values(1,'test');
SELECT LAST_INSERT_ID(); -- this will display the last inserted id
Related
I am using MySQL as a database for my application, my backend server is Nodejs, I have a query to insert records in a table and each record has to insert date. my problem I want to delete this record after two hours of inserting the date.
function setValue(sql) {
id = sql;
connection.query("SELECT subject_group_id,date FROM attendance WHERE subject_group_id = ?", [id], function (err, row) {
if (err) {
console.log(err);
} else if (row.length > 0) {
res.send({ 'success': false, 'message': 'Attendnace already exists' })
} else {
connection.query("INSERT INTO attendance (date,status,subject_group_id) VALUES (NOW(),?,?) ", [ status, id], function (err, row) {
if (err) {
console.log(err);
} else {
res.send({ 'created': true, 'alert': 'Attendnace had been created successfully' });
}
});
}
});
}
I used NOW() to insert the current date in the table for column date, so after two hours of this date I want this record to be deleted automatically without performing any action.
I think it can be achieved by adding a new column called expired and inserting statement insert date 2 hours ahead of the current date and then delete statement will do the comparison and delete the record based on this comparison. but my problem how to make the record delete automatically without submitting anything.
multiple ways
you can opt for setTimeout in js, the problem is when service goes down the last set of records won't be deleted
you can try scheduling inside mysql itself as well https://dev.mysql.com/doc/refman/8.0/en/events-syntax.html
I am trying to write a simple login page using node.js, HTML, and MySQL. A problem I ran into was adding entries to my sql db.
con.connect(function(err) {
if (err) throw err;
});
app.post('/create', function(req, res) {
var info ={
"usernamec":req.body.USERC,
"passwordc": req.body.PASSC
}
con.query('INSERT INTO users SET ?',info, function(err, result){
console.log(result);
});
});
Everything seems to be working except for the actual query, which returns undefined. What could I be doing wrong? The picture below is my database.
solution:
Change or Modify in Column name when you can assign the values (usernamec, passwordc) this one.
let info ={"username": req.body.USERC,"password": req.body.PASSC}
whenever you can insert the data Column name will be same as the Database table Col name.means Both are same not different
Firstly, please check your request params(USERC, PASSW)DataType and
Values.
then Second thing, console the error
con.query('INSERT INTO users SET ?',info, function(err, result){
if(err)
console.log(err);
console.log(result);
});
});
InCase Query Error you can get and resolved it.
Another Simple Way runs the Query in PHPMyadmin Manually.
Example:
INSERT INTO users SET `username`= 1 and `password` =`HELLO MYSQL`;
I'm trying to get results from multiple tables with one request from client. I first tried JOIN, but that would mean I'd have to have multiple rows that contain duplicate information. Then I decided to do a different query for each table separately, although I'm not sure know how cost efficient this is.
How should I construct the query so that it is accepted by Node.js? The one I'm trying to use now doesn't work if I don't use quotation marks to wrap the whole query, but if I do use them it complains there is an error with my query.
Here is the code for the query.
sql = "'SELECT * from `Ilmoittautuminen` WHERE `optunnus` LIKE ' + mysql.escape(reg.body.optunnus); 'SELECT * from `Jasenmaksu` WHERE `optunnus` LIKE ' + mysql.escape(reg.body.optunnus); 'SELECT * from `OppOikeus` WHERE `optunnus` LIKE ' + mysql.escape(reg.body.optunnus);"
console.log(sql);
connection.query(sql, function(err, rows){
console.log(rows)
if(err){
console.log(err)
res.json({
success: false,
message: err,
});
}else{
queryResponse(res, rows);
}
});
taking reference of https://github.com/mysqljs/mysql
passs multipleStatements:true in your connection param
and try with an exmaple
conn.query(`
SELECT * FROM posts limit 1;
SELECT * FROM Users limit 1;
`, (err, results)=>{
console.log(err, results)
});
After adding a product to the mysql database, I want to dump all the products with the latest product. This product is being added with an algorithm to the database and I want to list all the products immediately afterwards. Already tried "async", "promise" etc.
--When the table is empty--
connection.query("INSERT INTO `products` (id, name, price)", function (error, results, fields) {}); //inserted one row
connection.query("SELECT * FROM `products`", function (error, results, fields) {}); // show only []
after second insertion list query show only first row but not second. The main problem is this and table has two rows.
Thank you.
Query data when insert is done:
connection.query("INSERT INTO `products` (id, name, price)",
function (error, results, fields) {
connection.query("SELECT * FROM `products`", function (error2, results2, fields2){});
});
connection.query("INSERT INTO products(id, name, price)",
function (error, results, fields) {
if(error) return ....
else{
connection.query("SELECT * FROM products", function
(error,results,fields2){
var returned_data = results;
console.log(results);
//res.send(results);
})
}});
Would be the way to go, but check whether you're inserting the data the right way at all, since you haven't provided the way you do it, I doubt that any async method would fail you itself.
EDIT on request: You can pass the results to a variable, but you can only use it inside that function if you don't (because of its scope) , ie res.send or res.end it (if you're using this inside a request, which I'm guessing you are), or console.log it or just write it to a file.
user_id=3;
//Delete from table query working perfect
db.query("DELETE FROM table WHERE user_id=" + user_id, function(dberr,dbres){
addUserInventories(detail, req, function(err,invres){
getHomePageDataWithInvntory(req, function(request, response){
callback(null, response);
});
});
});
//Here add record in table
function addUserInventories(detail, req, callback){
//After insertion called following and working perfect
return callback(null, null);
});
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
db.query("SELECT * FROM table WHERE user_id=" + user_id, function(err, results){
callback(null, results); //Here result getting empty array
});
});
In above code Delete record and Insert record work perfect but Retrieving record is not working.
Note : There is no any syntax error in SQL Query and In log file it print SELECT * FROM table WHERE user_id=3
When I got this kind of error, I always save them with the same process :
console.log your query string before using it
Use a database client like Sequel Pro, MySQL Workbench for sql
Copy paste your query manually in the client and run it
Generally, you'll get a syntax error, just solve it in the database client and your solution should work
Database client is not mandatory as you can run the query with command line, but the client will be a simpler interface for you and is more likely to give you more details on your syntax error.
Can you try this process ? If you don't succeed in solving the syntax error in the database client, you can put the query here so we can help you
Just in case : with your example, I'll use this pattern to log the query if you have trouble to do it, this give you an idea of how to do it in your code
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
var queryString = "SELECT * FROM table WHERE user_id=" + user_id;
console.log(queryString);
db.query(queryString, function(err, results){
callback(null, results); //Here result getting empty array
});
});