How to insert one query result to another query as an input - mysql

When I try to run a query I am getting 500 Internal Error. I want to insert query2 result to query as a data.
Query:
exports.create = async (req, res) => {
try {
const connection = await mysql.createConnection(config.mysql.credentials);
var query2='select MAX(orders) from pdb_product';
const query = `insert into pdb_product (product_code, description, active, third_party,
orders) values ("${req.body.product_code}", "${req.body.description}", ${(req.body.active == 'on' ? 1 : 0)}, ${(req.body.third_party == 'on' ? 1 : 0)}, ${query2});`;
await connection.query(query);
res.redirect('/products');
} catch (e) {
utils.error500(req, res, e.message);
}
};
The error I am getting:
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 'select MAX(orders) from pdb_product)' at line 1
How can I resolve this?

You are missing a '(' bracket before the query2 parameter:
const query = `insert into pdb_product (product_code, description, active, third_party,
orders)
values ("${req.body.product_code}",
"${req.body.description}",
${(req.body.active == 'on' ? 1 : 0)},
${(req.body.third_party == 'on' ? 1 : 0)},
(${query2}));`;

Related

'ER_PARSE_ERROR' You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

I created in my model the const getbypage:
const getByPage = (page = 1, limit = 10) => {
return executeQuery(
'select * from clientes limit ? offset = ?',
[limit, (page-1) * limit]
);
}
in the controller:
router.get('/', async (req, res) => {
try {
const clients = await getByPage();
res.render('clients/list', { arrClients: clients });
} catch (err) {
console.log(err);
}
});
and the error is:
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
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 '= 0' at line 1",
sql: 'select * from clientes limit 10 offset = 0'
}
GET /clients - - ms - -
CAN SOMEBODY HELP ME?
https://dev.mysql.com/doc/refman/8.0/en/select.html shows you the reference documentation for the LIMIT clause:
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
There's no = in the syntax. You should just use OFFSET ?.
WRONG:
select * from clientes limit ? offset = ?
RIGHT:
select * from clientes limit ? offset ?

unable to insert dynamic rows into table using mysql and nodejs

I am trying to insert array of objects into the SQL but getting the following error
code: 'ER_PARSE_ERROR',
errno: 1064,
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 '?,?)' at line 1",
sqlState: '42000',
index: 0,
sql: 'INSERT INTO orderedproducts (order_id, product_id, quantity) VALUES ((19, 10, 2),?,?)'
This my testing array of object
var testData = [
{
productId: 10,
quantity: 2
}
]
I want to insert this object data into sql.
My current written code which is returning above error
let lastId = results.insertId
let orderedProductSql = 'INSERT INTO orderedproducts (order_id, product_id, quantity) VALUES (?,?,?)'
var testData = [
{
productId: 10,
quantity: 2
}
]
let values = testData.reduce((o, a) => {
let ini = []
ini.push(lastId)
ini.push(a.productId)
ini.push(a.quantity)
o.push(ini)
return o
}, [])
connection.query(orderedProductSql, [values], (err, results) => {
if (err) {
return connection.rollback(_ => {
throw err
})
}
connection.commit(err => {
if (err) {
connection.rollback(_ => {
throw err
})
}
connection.release()
callBack(null, results)
})
})
How can I solve this ??
Try doing something like this:
connection.query( "INSERT INTO orderedproducts SET order_id=?, product_id=?, quantity=?" , [lastid, productid, quantity] ,
function(err, result) {
if(err) throw err;
});
You need to use SET to insert data into your mysql database.

Mysql Error: trying to find columns in database

Im trying to insert user data into my mysql database but Im getting this error " sql: 'SELECT * FROM users WHERE undefined = ?' "
Here is my code :
find: function(user = null, callback) {
//if the user variable is defined
if(user) {
var field = Number.isInteger(user) ? 'id' : 'email';
}
// prepare the sql query
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result){
if(err) throw err;
if(result.length){
callback(result[0]);
} else {
callback(null);
}
});
},

How to insert values into Mysql.js table in Node express project

This is my use case.
First I insert data to the customer table.
Then I get the insertId for the customer.
Then I try to insert data into address table using that id.
async function createCustomer(req, res, next) {
const customer = {
type: req.body.type,
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email
};
const first_line = req.body.first_line
console.log("Customer from front-end", customer);
try {
let query1 = "INSERT INTO customer_supplier SET ?";
connection.query(query1, customer, (error, results) => {
if (error) {
console.log("Error", error);
} else {
let userId = results.insertId;
let query2 = "INSERT INTO address (id,first_line) VALUES ?";
connection.query(query2, [userId, first_line], (error, results) => {
if (error) {
console.log("error in address ==================================", error)
} else {
res.json({
results: results
})
}
})
}
});
} catch (error) {
console.log("error from", error);
res.json({
error: error
});
}
}
But when I try to insert data into the address table,
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 \'36\' at line 1',
sqlState: '42000',
index: 0,
sql: 'INSERT INTO address (id,first_line) VALUES 36' }
Before put this question on stackoverflow I tried so many variations in my insert statement and nothing works for me.
How do I achieve this?
Your sql is not written correct,you need to add () to wrap the value
let query2 = "INSERT INTO address (id,first_line) VALUES (?,?)";
Below is the grammar to use INSERT INTO
> INSERT INTO table_name (column1, column2, column3, ...)
> VALUES (value1, value2, value3, ...);
would you try this one
let query2 = "INSERT INTO address (id,first_line) VALUES ('userId', 'first_line')"
connection.query(query2, (error, results)

How to update multiple columns in mysql using nodejs

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}"`;