JavaScript MySql INSERT statement for multiple rows through URL - javascript

Good day !
I am trying to send an object array to my MySql Database through an url using an API.
Here is the code on my API :
app.get("/orderdetails/add", (req, res) => {
const {
item__,
Qty_Ordered,
Unit_Price,
Ext_Price
} = req.query;
const INSERT_ORDERDETAILS_QUERY = `INSERT INTO oe_details (item__,
Qty_Ordered, Unit_Price, Ext_Price) VALUES('${item__}', '${Qty_Ordered}',
'${Unit_Price}', '${Ext_Price}')`;
connection1.query(INSERT_ORDERDETAILS_QUERY, (err, results) => {
if (err) {
return res.send(err);
} else {
return res.send("successfully added order details");
}
});
});
And below is the function on my App :
addOrderDetails = _ => {
const o = this.props.o;
const summary = o.filter(function(obj) {
return obj.Quantity >= 1;
});
var url = "";
summary.forEach(function(e) {
url +=
"item__=" +
e.ExternalID +
"&Qty_Ordered=" +
e.Quantity +
"&Unit_Price=" +
e.Price +
"&Ext_Price=" +
e.ExtPrice +
"&";
});
url = url.trim("&");
fetch(`http://localhost:4000/orderdetails/add?${url}`).catch(err =>
console.error(err)
);
};
When I run addOrderDetails, I end up sending the following statement to MySql:
INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price)
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75')
Which is wrong... is there a way for me to add multiple rows to mysql database using the same concept ?
it works fine if I only have 1 row to add...
Help would be greatly appreciated !
Thanks,

To insert multiple rows, MySQL statement should be like
INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price)
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75'),
VALUES('C-2080,C-2081', '8,5', '18.75,18.75', '150,93.75'),
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75');
You can change your API to a POST call and send an array of your data to it, and within your API you can form the above query.
You can use a simple for loop to create such query.
let summary = [1,2,3,4] // dummy data
let INSERT_ORDERDETAILS_QUERY = `INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price) VALUES`
summary.forEach(function(data, i) {
INSERT_ORDERDETAILS_QUERY = `${INSERT_ORDERDETAILS_QUERY} (${data})`;
INSERT_ORDERDETAILS_QUERY = (i !== summary.length - 1) ? `${INSERT_ORDERDETAILS_QUERY}, ` : `${INSERT_ORDERDETAILS_QUERY};`;
})
Hope this helps!

Related

Get all items or data from API where they need to meet a condition to be fetched

I want to display a list of all items or data from an API source where the VirtualOrganization (or some other data) is the one i specify (like ATCclub). I use Axios to get the data.
Baicicly I only want to only fetch the JSON data from the API where the VirtualOrganization is the right one, and then display it.
Here is my code:
let data;
axios.get(URLBASE + '/flights/' + expert + '?apikey=' + APIKEY, {
params: {
virtualOrganization: "ATCclub"
}
})
.then(response => {
console.log(response.data.result);
if (response.data.result.virtualOrganization === "ATCclub") {
for (let i = 0; i < response.data.result.virtualOrganization.array.length; i++) {
document.getElementById("username").innerHTML = response.data.result.username;
document.getElementById("aircraftId").innerHTML = response.data.result.aircraftId;
document.getElementById("heading").innerHTML = response.data.result.heading;
document.getElementById("latitude").innerHTML = response.data.result.latitude;
document.getElementById("longitude").innerHTML = response.data.result.longitude;
document.getElementById("speed").innerHTML = response.data.result.speed;
document.getElementById("altitude").innerHTML = response.data.result.altitude;
}
}
})
.catch(error => console.error(error));
NOTE: I have managed to display one row from the JSON.
I found a solution after someone sent me a answer to "filter it after".
Then I came up with this:
// resF (result of flights)
const resF = response.data.result.filter(function (e){
return e.virtualOrganization === "ATCclub";
});

I want to return the result when all the queries in the loop is done(express.js, react.js, mysql)

I'm working on a side project using react and express.
I want to send the drop data of 7 days of a specific item in my database in the list for search.
So I wrote the code like this.
Use date(droped_at) = date(date_add(now(),interval -*${i}* DAY) and for loop.
for (var i = 1; i < 8; i++) {
var resultSql1 = `SELECT T.channel_name, T.channel_number, T.VALUE, T.num from(SELECT itemId, channel_name, channel_number, COUNT(*) AS VALUE, ROW_NUMBER() over(order by value DESC) NUM FROM item_drop_exception WHERE itemId = (SELECT itemId FROM item_exception WHERE itemid = '${id}') AND date(droped_at) = date(date_add(now(),interval -${i} DAY)) GROUP BY channel_name, channel_number) T WHERE T.NUM<=3 ORDER BY T.num ORDER BY T.NUM`
db.query(resultSql1, id, (err, data) => {
if (!err) {
list1.push(data);
if (list1.length == 7) {
res.send(list1);
}
}
else {
res.send(err);
}
})
}
But it doesn't work.
I know the method is wrong.
I think the next loop is going on before the query results come in, but I don't know what to do.
Is it right to bring in seven days of data like that?
I want to send the data to the front when all results are the append and complete.
It's not easy because I'm self-taught, I need help.
The query has a small error.
You have a double ORDER BY t.NUM at the end, so when you remove it the query runs. But if it gets you the right result, is only answerable , fi we had data
So
var resultSql1 = `SELECT T.channel_name, T.channel_number, T.VALUE, T.num from(SELECT itemId, channel_name, channel_number, COUNT(*) AS VALUE, ROW_NUMBER() over(order by value DESC) NUM FROM item_drop_exception WHERE itemId = (SELECT itemId FROM item_exception WHERE itemid = '${id}') AND date(droped_at) = date(date_add(now(),interval -${i} DAY)) GROUP BY channel_name, channel_number) T WHERE T.NUM<=3 ORDER BY T.num`
Would give you a result for every days
Turn your function call into a promise, then await it inside each loop, ensuring each db query runs one by one.
const { promisify } = require('util');
const dbQueryAsync = promisify(db.query);
async function getData(req, res) {
var { id } = req.params;
var list = [];
for (var i = 1; i < 8; i++) {
var resultSql1 = `SELECT ... `;
try {
var data = await dbQueryAsync(resultSql1, id);
list.push(data);
} catch(err) {
res.send(err);
}
}
res.send(list);
);

I want to tag users in a leaderboard, but instead it tags their id

I'm trying to make a leaderboard for my discord bot, and so far it works, but whenever I want to tag players in the embed it just sends something like this <#90258560912791> instead of: #wex
Here's my code:
if (message.content.startsWith(`${prefix}btop`)) {
if (message.member.roles.cache.find(r => r.name === "Walls")) {
var description = ""
let all = `SELECT userid , points FROM bufferpoints ORDER BY points DESC LIMIT 10;`
db.all(all, (err, row) => {
if (err) throw err;
const topembed = new Discord.MessageEmbed()
.setColor('#FF760B')
.setTitle(message.guild.name + "'s TOP Buffercheckers!")
.setTimestamp()
let i = 0;
row.forEach(function(row) {
i++;
if (row.points === 0) {
return;
}
description += ` ${i}. <#${row.userid}>` + `** - ${row.points}**\n`
})
topembed.setDescription(description)
message.channel.send(topembed)
})
}
}
And this is what I'm getting right now if somebody wondered
Thanks for your help!
I managed to solve the issue. When I saved userid I used message.author.id. I changed it to message.author.toString(). Bot saves data as <#125512> and then tags a user in the leaderboard.

Nodejs loop through the string and save into mongodb with auto increment length

In NodeJS I have string like this
"Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?";
I want to save each Qty with corresponding Package and Price. So lets say I have Package Two with Qty 3 then it would save 3 times with Package Two and Price would be 702.
So for now my code looks like this
const querystring = require('querystring');
const string = "Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?";
const items = string.split('?').filter(Boolean);
var TicketCountQuery = Ticket.count();
for(const query of items) {
// Parse the query string of each group
const { Package, Qty, Price } = querystring.parse(query);
for(let i = 0; i < Number(Qty); i++) {
console.log('Package Name ' + Package);
console.log('Package Price ' + Price);
TicketCountQuery.exec(function (e, count) {
if( count !== '' ) {
let TicketId = parseInt(count) + 1;
console.log(TicketId);
let ticketData = new Ticket({
_id : new mongoose.Types.ObjectId(),
ticketid : 'TKT '+ TicketId,
packagename : Package,
price : Price
});
ticketData.save((err) => {
if( err ) {
if( err.errors ) {
console.log('something went wrong');
}
}
else {
console.log('tickets saved');
}
});
}
});
}
}
Here the problem is it is just checking the mongodb collection only for the first time. That's why the ticketid is always same. I want that ticketid should be increment for each insert. But somehow its not working. So can someone tell me how to do this?
Any help and suggestion will be really appreciable.
The problem is that you're running the N exec queries before saving any ticket, this happens because the mongoose.exec runs asynchronously, so all the queries will return the same count. An easy fix is using async/await. According to the docs, .exec returns a promise if no callback is supplied, so we can easilly wait until the exec is done using await
const string = "Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?";
const qs = require('querystring');
async function processTickets(string) {
const TicketCountQuery = Ticket.count();
// We split the string into multiple valid query strings.
// We strip the empty item due to the '?' at the end using .filter(Boolean)
const items = string.split('?').filter(Boolean);
// We loop through each group
for(const query of items) {
// Parse the query string of each group
const { Package, Qty, Price } = qs.parse(query);
for(let i = 0; i < Number(Qty); i++) {
// We send the email here <Qty> times.
console.log('Package Name ' + Package);
console.log('Package Price ' + Price);
try {
// We wait until exec is done
// No other tickets can be fetched/saved, preventing your problem
const count = await TicketCountQuery.exec();
if( count !== '' ) {
let TicketId = parseInt(count) + 1;
let ticketData = new Ticket({
_id: new mongoose.Types.ObjectId(),
ticketid: 'TKT ' + TicketId,
packagename: Package,
price: Price
});
// We save each ticket one at a time
// So the next one will have the correct ID.
await ticketData.save();
console.log('ticket saved');
}
} catch(e) {
console.log('something went wrong', e);
}
}
}
}
processTickets(string)
.then(res => {
console.log('Tickets processed!')
})
.catch(err => {
console.error(err)
})

Replace in sqlite Update is not working

I am using SQLite update with replace to replace the string in the column when i run the query it makes the other column to be [].can anyone tell me why it occurs like this.
Query:
var old_farmerid = '"farmer_id":' + 1510829657942;
var new_farmerid = '"farmer_id":' + 1933;
var updateQuery = 'UPDATE load SET worker_details = replace(worker_details, ?, ?);';
$log.log(updateQuery);
return $cordovaSQLite.execute(Database.db, updateQuery, [old_farmerid, new_farmerid]).then(function (result) {
$log.log('updated sucessfully', result);
}, function (err) {
$log.log('error in update is', err);
});
And how can i make the old_farmerid to be like this '"farmer_id":1000'

Categories

Resources