Node Js mySQL updating multiple rows with array of arrays - mysql

I've got a dynamically assigned number of rows which I need to update. I created an array of arrays to keep all of those values and send them in one query. Each array contains three values A - a value which I want to update and B, C - keys necessary to recognize which row need to be updated.
var arrData = [];
arrData[0] = [43,54,67];
arrData[1] = [56,68,75];
arrData[2] = [43,67,75];
...
var query = "UPDATE my_table SET A_row = ? WHERE B_row = ? AND C_row = ?";
connection.query(query,[arrData], function(err,response){
if(err)
{
console.log(err)
}
else{ ... });
But then I get this error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? AND C_row = ?' at line 1
What do I do wrong here?

Each ? needs to resolve to an actual value. So you need a loop with a counter to set the index on the array and call the query ... something like,
...
for(cnt=0;cnt< length;cnt++) {
connection.query(query,arrData[cnt], function(err,response){
if(err){console.log(err)
else{ ... });

Related

How to exclude data which is already matched to the other table? MySQL CodeIgniter

I need to create a report of not submitted grades and fetch all data of not submitted grades.
I have two tables, tbl_college_grades and tbl_fm_college_curriculuminfo
1st table - tbl_college_grades - fetch data which have grades
2nd table - tbl_fm_college_curriculuminfo - fetch data with all subjects info
I need to hide or exclude data in tbl_fm_college_curriculuminfo in which tbl_college_grades already have.
Is there any way to achieve this?
Here is my model and query, I have tried to use NOT EXISTS but here is the error:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'EXISTS(SELECT tbl_college_grades.subCode FROM tbl_college_grades
WHERE tbl_co...'
Code:
function report(){
$this->db->join('tbl_college_grades','tbl_college_grades.subCode = tbl_fm_college_curriculuminfo.subjectCode','left');
$this->db->group_by('subject');
$this->db->where('NOT EXISTS(SELECT tbl_college_grades.subCode FROM tbl_college_grades WHERE tbl_college_grades.subCode = tbl_fm_college_curriculuminfo.subjectCode)');
$query = $this->db->get('tbl_fm_college_curriculuminfo');
return $query->result_array();
}
Use this
Preview in SQLFiddle
$this->db->group_by('tbl_fm_college_curriculuminfo.subject'); use proper table to subject. I assumed it was placed in tbl_fm_college_curriculuminfo
function report(){
$this->db->select('tbl_fm_college_curriculuminfo.*');
$this->db->from('tbl_fm_college_curriculuminfo');
$this->db->join('tbl_college_grades', 'tbl_college_grades.subCode = tbl_fm_college_curriculuminfo.subjectCode', 'left');
$this->db->where('NOT EXISTS (Select tbl_fm_college_curriculuminfo.subjectCode from tbl_college_grades WHERE tbl_college_grades.subCode = tbl_fm_college_curriculuminfo.subjectCode');
$this->db->group_by('tbl_fm_college_curriculuminfo.subject');
$query = $this->db->get();
}
group_by always comes at last (before data fetch ->get())

How to fix single quotes in parameterised mySQL query causing this issue?

const {tableName,recordId,idName}= req.query;
const arrayParam=[tableName,idName,recordId];
let sqlstmt="UPDATE ? SET status = 'deleted' WHERE ? = ?"
db.query(sqlstmt,arrayParam,(err,result) => {
if(err){console.log('Error occured while fetching user information',err)
res.send(err)
}
console.log(result);
res.send(result);
});
});
Error:
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''trainingRecords' SET status = 'deleted' WHERE 'recordId' = '10000107'' at line 1",
sqlState: '42000',
index: 0,
sql: "UPDATE 'trainingRecords' SET status = 'deleted' WHERE 'recordId' = '10000107'"
In the above snippet, from my understanding, it's the " ' " (single quotes added in the parameterization) that is causing the issue. Any suggestions to fix this?
Don't use prepared statements to inject table names or fields that you are using to filter or update. Try using this query.
UPDATE trainingRecords SET status = 'deleted' WHERE recordId = ?

MySQL 5.6.41 errno 1064: Creating a MySQL query with variables

I have a (currently localhost, but soon to be through AWS) Node.JS server with Express and I'm trying to update an RDS instance through a MySQL query when I'm getting the following error:
{ [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''history0' = 'http://localhost:3000/' WHERE id = 1' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'\'history0\' = \'http://localhost:3000/\' WHERE id = 1\' at line 1',
sqlState: '42000',
index: 0,
sql: 'UPDATE infected SET \'history0\' = \'http://localhost:3000/\' WHERE id = 1;' }
The POST request causing the error:
app.post('/history', function(req, res) {
var hist = 'history' + 0;
var sql = 'UPDATE infected SET ? = ? WHERE id = ?;';
connection.query(sql, [hist, req.body[0].url, 1]);
});
I'm using hist as a variable because I plan to have it in a loop, but I wasn't sure if the way I'm declaring it here is causing the issue so I left it as is. req.body is the output of JSON.stringify() called on call to chrome.history.search(). So I'm trying to get the URL of the entry at index 0.
I've tried a direct call to connection.query with a hard-coded string as follows:
connection.query("UPDATE infected SET history0='google.com' WHERE id='1'");
and it successfully updates the database, so I figure there's an issue with how I'm using the question marks to insert variables hist and req.body[0].url into the query, but I can't figure out what the issue is.
try with double "??" for the keys, this way:
app.post('/history', function(req, res) {
var hist = 'history' + 0;
var sql = 'UPDATE infected SET ?? = ? WHERE id = ?;';
connection.query(sql, [hist, req.body[0].url, 1]);
});

Pass array in Mysql query with nodejs

I have a simple query that I want to pass an array inside which has 5 items. I am using the mysql module so I know it can be done but am not doing the synatx right and therefore getting a syntax error.
Below is the query:
`UPDATE table1 SET table1.col=0 WHERE (table1.col2) IN = (?) AND table1.id=(SELECT ...);`,[arr]
//arr = [1,2,3,4,5];
I have tried:
`UPDATE table1 SET table1.col=0 WHERE (table1.col2) IN = (?,?,?,?,?) AND table1.id=(SELECT ...);`,[arr]`
but I still get a syntax error.
Adding on to Bill Karwin's answer, you can also pass an array to the MySQL query against the '?' placeholder in the same way
WHERE table1.col2 IN (?)
//arr = [1,2,3,4,5];
Passing arr along with the query will convert it to the required SQL string. The mysql module uses the 'SqlString.arrayToList' function from 'sqlstring' module internally for the transformation:
https://github.com/mysqljs/sqlstring/blob/8f193cae10a2208010102fd50f0b61e869e14dcb/lib/SqlString.js#L60
In my case, array inside of array is needed to get this working. Just array variable as parameter passed only first number to sql.
Here is an example: (Notice ids inside of array as the second parameter)
var sql = "SELECT * FROM table WHERE ID IN (?)";
var ids = [1,2,3];
pool.query(sql, [ids], function (err, result, fields) {
if(err) {
console.log(err);
}
else {
console.log(result);
}
}
The syntax of the IN() predicate does not use =.
WHERE (table1.col2) IN = (?,?,?,?,?)
should be
WHERE table1.col2 IN (?,?,?,?,?)
Tip: you can (and should) check syntax yourself in the documentation, so you can get answers more easily than posting to Stack Overflow.
https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_in

Not able to insert data into table using Nodejs

exports.creategroup= function(callback,name,email,firstname)
{
// var connection=pool.getConnection();
var connection=connect();
console.log(email);
console.log(firstname);
var query="CREATE TABLE "+name+"(membername varchar(50) NOT NULL,email varchar(50) NOT NULL)";
var query1="INSERT INTO'"+name+"'(membername,email) VALUES('"+email+"','"+firstname+"')";
console.log(query);
connection.query(query,function(err,result){
if(err)
{
console.log("ERROR:"+err.message);
}
else
{
if(result.length!==0)
{
console.log("DATA : "+JSON.stringify(result));
callback(err, result);
}
else
{
callback("Invalid Username", result);
}
}
//pool.returnConnection(connection);
});
//The insert into query gives an error. I can't figure out what syntax error i have made. Could someone please help. The table is being created. The error I am facing in the insert is
ERROR:ER_PARSE_ERROR: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near ''sad'(membername,email) VALUES('hunur','Sachin
Mallikarjun')' at line 1
here sad was passed as the argument for table name
You've put the table Name in ' ticks, that's not valid. Below will work:
var query1="INSERT INTO "+name+" (membername,email) VALUES('"+email+"','"+firstname+"')";
Please note that you absolutely shouldn't run a query like this as it is vulnerable to mysql injection. Use the escaped query node-mysql offers instead.
var query = "INSERT INTO ?? (??,??) VALUES (?,?)";
var values = [name,'membername','email',firstname,email];
mysql.query(mysql.format(query, values), function(err,result,tableInfo){/*...*/})
Like this, node-mysql prepares the query for you. Every ?? represents a table or column name while every ? stands for a value to be inserted. You can verify this by
console.log(mysql.format(query,values));