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
});
});
Related
I have no idea what I did wrong, it's supposed to output onto console "Query Initiated" after it grabs the result but nothing is logged and I have no idea what I did wrong. Yes, I know the syntax is ugly, I ran a prettifier over it and now it is incredibly ugly and I am too lazy to manually go through 200+ lines of code to fix it.
connection.query(`SELECT * FROM pedodb WHERE ID='${msg.author.id}'`),
function (err, result) {
query.on('result', function (err2, result2) {
callback(null, rows, fields);
console.log("Query Initiated")
The callback should be associated with the query function.
And the practice of using parameters is that they should be in separate parameters otherwise there are chances that it can lead to SQL injection.
connection.query(`SELECT * FROM pedodb WHERE ID = ?`, [msg.author.id],
function (err, result, fields) {
callback(null, rows, fields);
console.log("Query Initiated")
})
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 have been trying to setup my Nodejs MySQL database configuration. I found this passport.js config for MySQL on Github. The config works properly but there is a part that I do not understand.
var insertQuery = "INSERT INTO users ( email, password ) values ('" + email +"','"+ password +"')";
console.log(insertQuery);
connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
I am confused about the insertID field. The table I am using does not have a field called insertID. It does however have a field named ID. I tried changing that line to
newUserMysql.id = rows.Id;
bu doing so gives me:
Error: Failed to serialize user into session
Leaving it as it is gives me no error
Looks like insertID has nothing to do with the ID field of my table but I do not understand what it means
That probably represents LAST_INSERT_ID() which is the ID of the last row inserted.
The response of an INSERT is not "rows" but a result object, so maybe better named it'd be:
connection.query("...", function(err, result) {
newUserMysql.id = result.insertId;
return done(null, newUserMysql);
});
It's important to note that using Promises dramatically simplifies your code, and async/await can take that even further. This could be as simple as:
let result = await connection.query("...");
newUserMysql.id = result.insertId;
return newUserMysql;
Where that's inside an async function with a Promise-driven database library like Sequelize. You're not handling the potential errors in your first case. In the second you'll get exceptions which will wake you up when there's problems.
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)
});
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