I made the following code:
if (scIDExists) {
var x = con.query('SELECT posX, posY, posZ FROM players WHERE scID = '+socialID+'', function (err, result) {
if (err) {
console.log('The following error happened while selecting scID from [players]: ' + err);
throw err;
}
console.log(result);
});
}
The console.log(result) returns me this:
[ RowDataPacket { posX: 100, posY: 100, posZ: 100 } ]
I want it do return this:
100 100 100
Or atleast something I can work with.
How to? Thank you.
The following log:
[ RowDataPacket { posX: 100, posY: 100, posZ: 100 } ]
means that you have an array of a single element. This element is an instance of RowDataPacket class. You can access the properties like a normal object so you can access the value using:
console.log(result[0].posX) // returns 100
Related
I got my MySQL data printed in console.log() as console.log(result) and it works fine.
Now I need to use this result to define variable MyPlan in a different function.
This is how I got the results from MySQL db:
function load() {
var MySQL = SQL.createConnection(credentials)
MySQL.connect((err) => {
if(err) {
console.log(err);
process.exit(0);
}
for(var i = 0; i < 250; i++) console.log('\n');
console.log('Successfuly logged in!');
});
MySQL.query("SELECT plan FROM users WHERE username = 'asd123'", (err, rows) => {
if(err) { console.log(`[!] SQL Error: ${err}`); return; }
rows.forEach((results) => {
console.log(results); //output: RowDataPacket { plan: 300 }
});
});
}
load();
I need MyPlan: to be declared with a number 300 as stated above.
startMyPlan() {
//var theoric = 10;
this.botCountInt = setInterval(() => {
let json = {
connected: 0,
MyPlan: //300
};
this.send(json);
}, 100);
}
I tried to define results in first function like this:
rows.forEach((results) => {
myresult = results //first option
// OR LIKE THIS:
this.myresult = results; //second option
console.log(results);
});
and write it in startMyPlan() as
let json = {
connected: 0,
MyPlan: this.myresult
};
But first option gave me error myresult is not defined and second option gave me different error: Cannot set properties of undefined(setting 'myresult').
EDIT: I guess my problem is that results won't give me correct output OUTSIDE that function where it's created. It returns undentified when I try to run console.log(results); once it's run outside load() function
So, as per my understanding, you have not defined the myresult variable in any scope.
The first option will work if you do var myresult=undefined just before rows.forEach((results) => call.
One example:
var rows = [{ "test": "foo1" }, { "test": "foo2" }, { "test": "foo3" }, { "test": "foo4" }];
var myresult;
rows.forEach((results) => {
myresult = results //first option
console.log(myresult);
});
console.log(myresult);
I am not sure what exactly you want to do with myresult. But I think above example will be enough to understand things.
I started to develop some Nodejs APIs (with Express) today to retrieve some data from MySQL. I am familiar with some programming languages like Python but not with javascript. My first API is now working, but I'm not sure whether it's optimal or not. I am also not understanding some of its behavior.
The values I would like to retrieve :
label
description
latitude
longitude
photos, an array of id_photos
1), 2), 3), and 4) are unique values from a first MySQL table;
the id_photos of 5) are multiple rows from a second MySQL table.
Here is the code I wrote :
PoI.findById = (idPoI, result) => {
sql.query(`SELECT label,description,ST_Y(geo) AS latitude,ST_X(geo) AS longitude FROM poi WHERE id_poi=${idPoI}`, (err, res1) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res1.length) {
sql.query(`SELECT id_photo FROM photo WHERE id_poi=${idPoI}`, (err, res2) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("found poi: ", {...res1[0],photo:res2});
result(null, {...res1[0],photo:res2});
return;
});
}
// result({ kind: "not_found" }, null);
});
};
EDIT : As highlighted by nbk in the comments, this code is vulnerable to sql injections. The query now looks like that sql.query('SELECT label,description,ST_Y(geo) AS latitude,ST_X(geo) AS longitude FROM poi WHERE ?', args, (err, res1) => {}) with args = {id_poi: idPoI};
My questions:
Is it a correct way to combine the results from two different MySQL queries ?
The console shows found poi : label: 'Museum...' ........ photo: [ RowDataPacket { id_photo: 1 }, RowDataPacket { id_photo: 2 } ]; Thus, the data from the first query look correctly handled, but the data from the second query appear as "RowDataPacket"; It does not seem to affect the final api output though; Is it an issue ?
If I uncomment result({ kind: "not_found" }, null);, I get ERR_HTTP_HEADERS_SENT, why ?
I am facing problem while updating multiple rows in table.
following is my data
const update_Data = upins_data.map(
upins_data => [{
upin_id: upins_data.upin_id,
media_type: upins_data.media_type,
land: upins_data.land
}]
);
it has multiple values.
i have tired following code
var updateSecTab = `UPDATE tb_bid_upins SET upin_id=?,media_type=?,land=? WHERE bid_id = ?`;
var query = db.query(updateSecTab,[update_Data,cond],function(error,result,fields){
if (error) { /**If error while inserting into table 2 it rowback the Transaction */
console.log('in err 1');
return db.rollback(function () {
throw err;
});
}
db.commit(function (err, result3) {
if (err) {
console.log('in err 2');
return db.rollback(function () {
throw err;
});
}
/**Send success result to front end */
console.log('success!');
res.send(JSON.stringify(result));
})
});
console.log(query.sql);
When i print the query it gives result as follows
UPDATE tb_bid_upins SET upin_id=('[object Object]'), ('[object Object]'),media_type=1,land=? WHERE bid_id = ?
Hello everyone i have tried following solution and it works.
var upins_data = [ { upin_id: 1, media_type: 5, land: 'Rakhiyal Circle' } ],
[ { upin_id: 3, media_type: 6, land: 'Rakhiyal Circle' } ]
var cond = 1
i have added above two variable in single array as follows
const update_Data = upins_data.map(
upins_data => {
return {
bid_id: cond,
upin_id: upins_data.upin_id,
media_type: upins_data.media_type,
land: upins_data.land
}
}
);
than i have used foreach on update_Data array and i have created multiple sql quires using mysql foramt function.
var queries = '';
update_Data.forEach(function (item) {
let sql = mysql.format("UPDATE tb_bid_upins SET upin_id=?,media_type=?,land=? WHERE bid_id = ? ;", [item.upin_id,item.media_type, item.land, item.bid_id]);
queries += sql;
console.log(sql);
});
than i have passed above queries variable in sql query as follows
db.query(queries,(err,result)=>{
if(err){
console.log('err',err);
}else{
console.log('result',result);
}
});
above code works for me in nodejs .
if anyone wants to improve than they can.
thank you
I am trying to add in the Node.js id to session retrieved from the database.
I edits the steam-login for this purpose, but everything except the passing of the id works. I know why it does not work. This is because the query in node.js is asynchronous. Unfortunately, I do not know how to solve it, to return it in a function.
req.user = user;
connection.query("select * from users where steamid = "+user.steamid, function(err, row){
if(err) {
throw err;
} else {
req.user.id = row[0].id;
//And now when i trying to console.log(req.user.id) i will se the id from database.
}
});
//But here when i try console.log(req.use.id) i see undefined.
I need to set req.user.id = id from database. i can't do it like up, because this dont work.
As soon as your get the query result, return it:
user.find('first', { where: "steamid = " + player.steamid }, function(err, row) {
if (row === undefined || row === null) {
user.save();
} else {
user.set('id', row.id);
user.save();
}
});
user.find('first', { where: "steamid = " + player.steamid }, function(err, row) {
return Promise.resolve({
id: row.id,
_json: player,
steamid: steamID,
username: player.personaname,
name: player.realname,
profile: player.profileurl,
avatar: {
small: player.avatar,
medium: player.avatarmedium,
large: player.avatarfull
},
hascsgo: hascsgo
});
});
I have this node msnodesqlv8 connection and I am counting the number of records from one table. I am getting the result as { total: 26 } and the expected result should be 26. Here is my code:
pool.connect().then(() => {
pool.request().query('SELECT count([TaskID]) as total FROM [db_test].[dbo].[tb_test]', (err, result) => {
myResults = result.recordset[0];
console.log(myResults);
})
});
As you are getting data in object form. now you have to access the object from the result.
pool.connect().then(() => {
pool.request().query('SELECT count([TaskID]) as total FROM [db_test].[dbo].[tb_test]', (err, result) => {
myResults = result.recordset[0].total;
console.log(myResults.total); // it should provides you expected result
})
});