I am new in nodejs and mysql.
I am have an array of objects that i get from post and want to insert it to mysql database.
If the data already exist then run the update query to database.
The problem is Insert query not loop the entire array. it just insert the last entry of Array. Here my code:
Array Data:
bukukasData
[{transactionid: '562018965521',
tanggal: '2018-06-05',
kodeakun: 0, item: 'Saldo',
debit: 100000, credit: 0,
saldo: 100000},
{transactionid:'562018595664',
tanggal:'2018-06-05',
kodeakun: 0,
item: 'Test Data',
debit: 0,
credit: 5000,
saldo:95000}]
NodeJS Query
app.post('/api/addbukukas', function(req, res) {
let bukukasData = req.body.bukukasData;
var status = '';
for (var i = 0; i < bukukasData.length; i++) {
var transactionid = req.body.bukukasData[i].transactionid;
var kodeakun = req.body.bukukasData[i].kodeakun;
var item = req.body.bukukasData[i].item;
var debit = req.body.bukukasData[i].debit;
var credit = req.body.bukukasData[i].credit;
var saldo = req.body.bukukasData[i].saldo;
var tanggal = req.body.bukukasData[i].tanggal;
db.query('SELECT COUNT (*) AS rowCount FROM bukukas WHERE transactionid = ?', [req.body.bukukasData[i].transactionid], function(error, result) {
var rows = result[0].rowCount;
if (rows > 0) {
db.query('UPDATE bukukas SET transactionid=?, kodeakun=?, tanggal=?, item=?, debit=?, credit=?, saldo=? WHERE transactionid = ?', [transactionid, kodeakun, tanggal, item, debit, credit, saldo, transactionid],
function(err, result) {
if (err) {
status = 'Update Gagal';
} else {
status = 'Update Success';
}
})
} else {
db.query('INSERT INTO bukukas (transactionid, kodeakun, tanggal, item, debit, credit, saldo) VALUES (?,?,?,?,?,?,?)', [transactionid, kodeakun, tanggal, item, debit, credit, saldo], function(err, insertresult) {
if (err) {
status = 'Insert Gagal';
} else {
status = "insertresult";
}
})
}
})
}
console.log(status);
return res.json({ status: status });
});
With this code the only data that getting inserted to database just the last data in array. How can i insert all the data in Array to database?
Thanks
Use let instead of var. That will avoid this problem.
The source of this problem is, that in JavaScript the for-loop loops through the variable i and starts bukukasData.length times the db query. The parameter is given as reference. Since the loop iterates very fast, the first sql statement ist started with i set to the last value and all db-statements are executed with i set to bukukasData.length. let was introduced to JavaScript to fix problems like this. With let it will create a copy of the variable in the background.
Related
i have a simple insert query that looks like that:
let sql = "INSERT into users(name, date) VALUES ('"+name+"', '"+date+"')";
connection.query(sql, (err, result) => {
if(err) {
res.status(500);
} else {
res.send(result) // we have here an object that has only the inserted id
}
});
which i really want is getting the inserted row data not just the id without making another select query to get them.
is there is a way to make that happens in one query?
If you are using:
// include mysql module var mysql = require('mysql');
The mysql module won't return data on the insert's query. It's returning:
Number of rows affected, Number of records affected with the warning, Message
If you wanna get data that you inserted, you should use a query builder or ORM like Sequelize. Sequelize Documentation.
You can get last inserted id using the code below:
SQLconnnection.query(sql, (err, result) => {
if(err) {
console.error(err);
} else {
console.log(result) ;
/*Output=>{affectedRows: 1
changedRows: 0
fieldCount: 0
insertId: 1 =>Last inserted ID Here
message: ""
protocol41: true
serverStatus: 2
warningCount: 0}*/
console.log(result.insertId);//=>last inserted id get
}
});
You can use this to retrieve the
let sql = "INSERT into users(name, date) VALUES ('"+name+"', '"+date+"') ; SELECT * FROM users WHERE id = SCOPE_IDENTITY()";
connection.query(sql, (err, result) => {
if(err) {
res.status(500);
} else {
res.send(result) // we have here an object that has only the inserted id
}
});
SCOPE_IDENTITY() Returns the last identity value inserted
I have a problem with SQL in node.js.
I have an array 'data' which contains some data returned from the async function and I want to put it into MySQL database if there's no result with the same data. There are some duplicated objects in array but I want to put just one into database.
Function example:
async function data_name(param){
var data = [];
data.push({
name: param,
sname: 'sname',
url: 'url',
report: 'report'
});
return data;
}
Then I run following code:
var data = await data_name('name');
data.forEach(item=>{
var chk = "SELECT * FROM `?` WHERE `name` = ? AND `sname` = ?;";
con.query(chk, [tablename, item.name, item.sname], function(er,items){
if(er) throw er;
if(items.length < 1){
var insert = "INSERT INTO `?` (name, sname, url, report) VALUES (?,?,?,?)";
con.query(insert, [tablename, item.name, item.sname, item.url, item.report], function(erg,added){
if(erg) throw erg;
console.log('Item added: ' + item.name);
});
}
else{
if(items[0].report != item.report){
var upd = "UPDATE `?` SET report = ? WHERE id = ?";
con.query(upd, [tablename, item.report, items[0].id], function(ere,edited){
if(ere) throw ere;
console.log('Item updated: ' +items[0].name);
});
}
}
//broken code below
var adc = "SELECT * FROM `links` WHERE `link` = ?;";
con.query(adc, item.url, function(erc, results){
//tried also with: results[0] === undefined || results[0] === null
var test = item.url + ' ' + results.length;
console.log(test);
if(results.length < 1){
var add_c = "INSERT INTO `links` (link_name, link_url) VALUES (?,?)";
con.query(add_c, [item.name, item.url], function(era, a_link){
if(era) throw era;
});
}
else{console.log('Record exists');}
});
});
});
The first SQL works great: it inserts all records to database, there are no duplicates and it updates values if it is required.
Second SQL (mentioned by a comment in code that I put before) doesn't work properly if the database is empty. It duplicates records in database (after running it database has 470 records while every record is duplicated about 8 times).
test variable prints for eg:
https://google.com 0
https://google.com 0
https://facebook.com 0
https://facebook.com 0
https://google.com 1
https://facebook.com 0
https://google.com 0
The problem exists only if a database is empty (if I run the code second time, the second SQL doesn't insert records new records and print in console 'Record exists'
Any ideas what can be reason of that?
I'm trying to update a TEXT field in a MYSQL table. I can't get the UPDATE query to work, even though the original INSERT attempt works fine when the user doesn't exist.
The purpose of the function is to INSERT new row if the user doesn't exist yet, and to UPDATE the textColumn (that always contains a JSON) if the user already exists in the table.
My code:
let first = 'jake';
let last = 'mcdonald';
let first_json = JSON.stringify({a:7, b:7});
let second_json = JSON.stringify({a:'updated'});
const row = {
name: first,
last_name: last,
textColumn: first_json,
}
db.query(`SELECT * FROM tableName
WHERE name="${first}"
AND last_name="${last}"`, (err, result) => {
if (err) console.log(err);
if (result.length < 1) {
db.query(`INSERT INTO tableName SET ?`, row, (err, result) => {
console.log('NEW ROW CREATED: ', result);
})
} else if (result.length > 0) {
console.log('ROW EXISTS');
db.query(`UPDATE tableName
SET textColumn=${second_json}
WHERE name="${first}"
AND last_name="${last}"`, (err, result) => {
console.log('UPDATED: ', result);
}
)
}
}
)
the else if section is what is giving me issues: I reach the inside console.log('ROW EXISTS') but the Update query logs "undefined".
The same UPDATE query works if I try to UPDATE tableName SET name="someNewName" WHERE last_name="original_last_name", but nothing happens when I try to UPDATE the textColumn.
i have a Json Object and want to loop thorugh it. In my loop I want to execute a select query and save it result to another json Array.
So I start with a loop, performe a mysql query and want just log the results:
for (var x = 0; x < obj.length; x++) {
var query = connection.query('SELECT Id, date FROM tbl1 WHERE Id LIKE '+ mysql.escape(obj[x].ident) +'; SELECT Id, date FROM tbl WHERE Id LIKE '+ mysql.escape(obj[x].ident) +' ORDER BY date DESC Limit 1 offset 1', function (error, results, fields) {
if (error) {throw error;}
if (!error) {
console.log("resultset"+results); //<- Here I get the right result
console.log("ID: "+results[0].Id); //<- UNDEFINED
console.log("ID-LAST-entry: "+ results[1].Id); //<- UNDEFINED
} });
The Problem is that for booth results (0 and 1) i get = UNDEFINED.
Where is my mistake?
From the value of results, You can see that it is NOT an array of objects instead it is an array of arrays where each item is an object.
You need to iterate inner array to get the Id. See the snippet below. Parsing the result into JSON and then reads the required data.
if (!error) {
var parsedResults = JSON.parse(JSON.stringify(results));
var outerArraySize = parsedResults.length;
for (var outerIndex = 0; outerIndex < outerArraySize; ++outerIndex) {
var innerArraySize = parsedResults[outerIndex].length;
for (var innerIndex = 0; innerIndex < innerArraySize; ++innerIndex)
console.log("ID: " + parsedResults[outerIndex][innerIndex].Id);
}
}
How to update the multiple columns in MySQL using node.js:
var query = 'UPDATE employee SET profile_name = ? WHERE id = ?';
connection.query(query,[req.name,req.id] function (error, result, rows, fields) {
but I have to update profile_name, phone,email, country, state, address at once.
How can I do that, can anyone suggest.
Simply add all columns in set:
var query = 'UPDATE employee SET profile_name = ?, phone =?, .. WHERE id=?';
connection.query(query,[req.name,req.phone,...,req.id] function (error, result, rows, fields) {
👨🏫 To update your multiple columns in mysql using nodejs, then You can do it like this code below: 👇
const query = 'UPDATE `employee` SET ? WHERE ?';
connection.query(query, [req.body, req.params], function(err, rows) {
if(err) {
console.log(err.message);
// do some stuff here
} else {
console.log(rows);
// do some stuff here
}
});
💡 Make sure your req.body is not empty and the field in your req.body it's same with the field in your employee table.
If your req.body is undefined or null, then you can add this middleware to your express server:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
I hope it can help you 🙏.
UPDATE statement syntax :
UPDATE <TableName>
SET <Col1> = <Val1>,
<Col2> = <Val2>,
....
WHERE id = ?
If you have multiple columns update, and need to take the values from the Object,
you can do the following-
let data = {
"table": {
"update_table":"dlrecustomer"
},
"result": {
"pro":"blre",
"pro_id":"BFCA",
"MOBILE":"9506443333",
},
"keys": {
"CUSTOMER":"27799144",
"APPLICATION":"5454642463"
},
}
let update_set = Object.keys(data.result).map(value=>{
return ` ${value} = "${data.result[value]}"`;
});
let update_query = `UPDATE ${data.table.update_table} SET ${update_set.join(" ,")} WHERE CUST_ID = "${data.keys.CUSTOMER}" AND APPL_ID = "${data.keys.APPLICATION}"`;