NodeJS - Mysql Error while insert data to database - mysql

I got a function like getItemPrice in nodeJS. But while trying to inserting datas there is a error occuring. Can't write any dynamic value inside VALUES(item.Id, value.lowest_price).
I've tried lots of things bot none of work.
con.query('SELECT game_item.id as itemId, steam_app_game.app_id as gameId, game_item.name, steam_app_game.id FROM steam_app_game LEFT JOIN game_item ON steam_app_game.id = game_item.app_game_id', function(err, rows, fields) {
var counter = 1;
rows.forEach(function (item,index) {
setTimeout(function(){
market.getItemPrice(item.gameId, item.name).then(function (value, err) {
if(err) throw err;
var lowest = value.lowest_price
con.query('INSERT INTO game_item_spec(game_item_id,price) VALUES (item.itemId,value.lowest_price )')
counter ++;
});
}, index * 5000);
});
});
Here is the error.
ER_BAD_FIELD_ERROR: Unknown column 'value.lowest_price' in 'field list'
at Query.Sequence._packetToError (F:\Xamp\htdocs\steam-trade-bot\node_modules\mysql\lib\protocol\sequences\Sequence.js:47
:14)

I solved this using parameter statements in nodeJs. Single insert into doesn’t work for if the data has special chars

A query must be a string, so to inject some variables inside you can use ES6 syntax with template string.
Here the working code:
con.query('SELECT game_item.id as itemId, steam_app_game.app_id as gameId, game_item.name, steam_app_game.id FROM steam_app_game LEFT JOIN game_item ON steam_app_game.id = game_item.app_game_id', function(err, rows, fields) {
var counter = 1;
rows.forEach(function (item,index) {
setTimeout(function(){
market.getItemPrice(item.gameId, item.name).then(function (value, err) {
if(err) throw err;
var lowest = value.lowest_price
con.query(`INSERT INTO game_item_spec(game_item_id,price) VALUES (${item.itemId}, ${value.lowest_price} )`)
counter ++;
});
}, index * 5000);
});
});

I recommend that you use node async https://caolan.github.io/async/, use series together with eachOfSeries

Related

Struggling to print multiple MySQL rows to a web page using Node.js

Trying to build a simple web app using Node.js. One of the pages requires multiple rows from one of my SQL table columns to be printed out like so:
Here is the most recently added string from column X
Here is the second most recently added string
Here is the third
Here is the fourth
Here is the fifth
I've got the hang of printing the first row using something like this:
var q = 'SELECT mycolumn AS string FROM users';
connection.query(q, function (error, results) {
if (error) throw error;
var string = results[0].string;
res.render('thanks', {string: string});
});
});
However, I can't figure out how to print the results from rows 1-5. Closest I've got from Google is:
connection.query('SELECT mycolumn AS string FROM users LIMIT 5', function (error, results) {
if (error) throw error;
var string = JSON.stringify(results);
res.render('thanks', {string: string});
});
});
but this gives me [{"mycolumn":"The content I'm trying to isolate"},{.....etc ] as the output and I can't figure out a way to clean that up.
I believe that by specifying results[0] you are only getting the record with the index of 0 - which should be the first one.
Here is a sample of select query in one of my apps:
app.get('/categories', async(req, res) => {
try {
const allCategories = await pool.query("SELECT id, title FROM categories WHERE visible=true ORDER BY id desc");
res.json(allCategories.rows);
} catch (error) {
console.error(error.message);
}
});
You can see I don't have the [0] on my rows result.
Solved it:
connection.query(q, function (error, results) {
if (error) throw error;
var string1 = results[0].string;
var string2 = results[1].string;
var string3 = results[2].string;
res.render('thanks', {string1: string1, string2: string2, string3: string3});
});
});```

Undefined push to array - Basic Application using ExpressJs and MySQL

First of all, I have to tell you I'm pretty noob in this "universe". I'm using: ExpressJs, MySql, Body-Parser, Express-session, Ejs template for creating an Basic Contacts Application in Node.
My database is composed from 3 tables:
user (user_id, first, second name, username, password)
contacts (ct_id, first, second name, phone numb.)
user_contacts (user_id, ct_id) --> foreign keys for user and contacts
I want to listing on /myProfile page all details about user and his contacts.
I don't know how to handle the select queries.
So, after some documentation I did this:
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
console.log(result);
var queryArray = "";
for(var i = 0; i < result.length; i++){
queryArray += `SELECT * FROM contacts WHERE ct_id= ${result[i].ct_id}; `;
}
console.log(queryArray);
conn.query(queryArray, function (err, result) {
if(err) throw err;
console.log(result);
res.render('myProfile/contacts', {
title: `${req.session.user_nickname}'s Contacts`,
data: result
});
});
});
But I have an error
ER_PARSE_ERROR: You have an error in your SQL syntax;
..when queryArray.length > 1
I searched and it's something about Multiple statement queries but I dont know how to solve it.
Edit 2:
I modify my code..
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
var datas = [];
for(var i = 0; i < result.length; i++){
getContacts = function(query){
conn.query(query, function (err, result) {
console.log('Creating data');
data = {
user: req.session.user_nickname,
contact:{
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
}
}
return data;
});
}
console.log('Send data to array');
datas.push(getContacts(`SELECT * FROM contacts WHERE ct_id = ${result[i].ct_id}`));
}
console.log(datas); // [ undefined, undefined ]
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: datas
})
});
But now my array contain undefined objects?? Any solution?
Maybe is something about scope?
My result:
Send data to array
Send data to array
[ undefined, undefined ]
Creating data
Creating data
I push the object to array before creating it. How is it possible?
1797,
I noticed you have several small queries grabbing the contact info for a given user. You could simplify your code by combining your queries into a single one. Often times 1 big query is more efficient (plus it's easier to maintain). I'm using a join. More info here.
const contacts = [];
const query = "
SELECT c.*
FROM user_contact uc
JOIN contact c ON uc.contact_id = c.contact_id
WHERE uc.user_id = ?
GROUP BY c.contact_id
";
conn.query(query, req.session.user_id, (err, results) => {
if (err) throw new Error(err);
// it seems that this could just be 'contacts = results' since they
// have the same structure
contacts = results.map(result => {
return {
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
};
});
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: contacts
});
});

Query in NodeJS with MySQL

I got this code and I need to create another query to send data in a form.... I tried copying this one but it didn't work ....
any idea how to proceed ?.
app.get('/', function (req2, res2) {
console.log('Welcome in console');
var sqlQuery = 'select * from transvip.transvip_regions';
// var sqlQuery2 = 'select * from transvip.transvip_agreement_favourite_address';
connection.query(sqlQuery, function (error, results, fields) {
if (error) throw error;
//console.log("results in console: ");
//console.log(results);
res.render('home', {
title: "Rounting and Assignment Grouped Trips",
results: results
});
});
});

Select and Insert in node loop not working as expected

I am trying to insert data in table before checking that Is it already exist in database table? If exist then loop continue with console message "Already exist" and If not exist then I try to insert in table. But some of the records are already in database table then also Inserted in table.
Following My NodeJS Code
(function loop(index){
if(index==apires.items.length){
console.log("Cron completed");
res.send("Cron completed");
return false;
}
inventoryObj = apires.items[index];
hash_name = inventoryObj.market_hash_name;
db.query('SELECT market_hash_name FROM inventory_master WHERE market_hash_name = "'+hash_name+'"', function(err,result, fields){
if(result.length){
console.log('already exist');
loop(++index);
}
else
{
var post = {data_here};
var query = db.query('INSERT INTO inventory_master SET ?', post, function (error, results, fields) {
if (error) throw error;
loop(++index);
});
}
});
})(0);
I guess this is happening due to the asynchronous behavior of your code. You can use async library to make it working, this will allow your code to execute on element at a time. Example
// assuming apires.itemsis an array
async.each(apires.items, function(inventoryObj, callback) {
hash_name = inventoryObj.market_hash_name;
db.query('SELECT market_hash_name FROM inventory_master WHERE market_hash_name = "'+hash_name+'"', function(err,result, fields){
if(result.length){
console.log('already exist');
callback('success'); // go for next iteration
}
else
{
var post = {data_here};
var query = db.query('INSERT INTO inventory_master SET ?', post, function (error, results, fields) {
if (error) throw error;
callback('success'); // go for next iteration
});
}
});
}, function(err) {
//once all finished, it will come here,if no error occurred then err will be null
});

Node.js - mysql: Bad field Error

I parse a big csv and insert row per row into my mysql tables.
After parsing I do a lot of calculation and transforming and save it to a new Object
obj.push({
"ID": value.id,
"col1": value.calc1,
... });
After the Object is complete I do:
async.forEach(obj, function (Insertobj, callback) {
var query = conn.query('INSERT INTO table SET ?', Insertobj);
},function (err){
if (err) {
console.log(err);
console.log('failed to process');
}}
After running through the obj I get =>
Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'field list'..
But he inserts the complete Object into my table! I don't have any column called NaN or empty cols. How can I debug it? I try to set the console.log to err.sql, but he print "undefined". Using debug:true in connection didn't help me.
I think you have misunderstood how escaping mysql values works using the node js module. The error is due to you not specifying what column you want to update. In addition to this, the escaped values should be filled in using an array instead of an object. With values being in the order they are escaped in the query. Your code could look as follows:
valuesarray.push([
value.id,
value.calc1
]);
async.forEach(valuesarray, function ( insertarray, callback ) {
var query = conn.query('INSERT INTO table SET ID = ?, col1 =
?', insertarray);
},function (err){
if (err) {
console.log(err);
console.log('failed to process');
}
});