INSERT into sql error - internal server error - mysql

I am trying to insert some data on my app. On my db.js:
usersDB.create = async (name, age, contact) => {
return new Promise((resolve, reject) => {
pool.query(
"INSERT INTO users(name=?, age=?, contact=?) VALUES(?,?,?)",
[name, age, contact],
(err, results) => {
if (err) {
return reject(err);
}
return resolve(results);
}
);
});
};
Then on my router.js:
router.post("/", async (req, res) => {
try {
let results = await db.create(
req.body.name,
req.body.age,
req.body.contact
);
res.send({ message: "Created users" });
} catch (error) {
console.log(error);
res.sendStatus(500);
}
});
This however, returns an INTERNAL SERVER ERROR on postman and returns the ff on my console:
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 '='Your Builder', age=25, contact=689566) VALUES(?,?,?)' at line 1"
Any idea what am I missing here? How do I fix it?

This line:
"INSERT INTO users(name=?, age=?, contact=?) VALUES(?,?,?)"
Contains a SQL Syntax error. Change it like this:
"INSERT INTO users (name, age, contact) VALUES (?,?,?)"
You first list the fields, without assigning anything to the single field, then you list the values you want to insert.

Related

MySQL placeholders throw error on WHERE clause

I am using MySQL placeholders and create promise to use them with async await.
selectTickets: (variable) => {
const sqlStatement = `SELECT * FROM tickets WHERE userID = ?`;
return new Promise((resolve, reject) => {
db.query(sqlStatement, variable, (error, response) => {
if (error) return reject(error);
return resolve(response);
});
});
},
i tried even to create the statement with interpolation and gave me an error:
"Unknown column 'undefined' in 'where clause'"
This is my code. But when I am using it in react, I am getting Error 500 status saying that the statement is incorrect.
ode: '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: 'SELECT * FROM tickets WHERE userID = ?'
I tried alot of other methods. But other functions that uses same type of function with same type of statement are working just fine.
In react I have this call:
const URL_TICKETS_BY_USERID = 'http://localhost:3000/api/get-tickets';
const config = {
headers: { Authorization: `Bearer ${user.token}` }
};
const userID = user.userID;
axios.get(URL_TICKETS_BY_USERID,
userID,
config
)
.then(data => console.log(data))
.catch(error => console.log(error))
Can i have some help?
The problem lies with your db.query() call. The second parameter should be an array, even for single values. This should work:
db.query(sqlStatement, [variable], (error, response) => {
if (error) return reject(error);
return resolve(response);
});
Also axios get() takes two parameters: url and config (optional). This means that any params should be part of that config object:
const config = {
headers: { Authorization: `Bearer ${user.token}` },
params: {
id: user.userID
}
};
axios.get(URL_TICKETS_BY_USERID, config)
Alternatively pass it as a GET parameter in the URL:
axios.get(URL_TICKETS_BY_USERID + "?id=" + user.userID, config)
In my case it was the question mark. In some database systems, the question mark is used as a placeholder for values that are passed in separately. However, it seems that in my case, the database system is not recognizing the question mark as a placeholder, and is interpreting it as part of the query.
So changed the query to:-
const q = `SELECT * FROM list WHERE userid = ${listId}`;
I passed the variable inside the query and it works now

Node.js post API is not working with MySQL database?

I am trying to make a post API using Node.js using MySQL database, API is giving no response only throwing error - code: 204
I am inserting data using Postman -
{
"articleid":"1233wawdasyyyd4",
"userid": "123uu"
}
In MySQL table there are 4 fields.
id(unique and incrementing) articleid (varchar) userid (varchar) datetime (current timestamp)
var deletelog = (req, res) => {
const articleid = req.body.articleid;
const userid = req.body.userid;
var sql = `INSERT INTO deletearticles_log (articleid, userid)
VALUES ('"+articleid+"', '"+userid+"')`;
connection.query(sql,[articleid, userid], function (error, results, fields) {
if (error) {
res.send({
"code":400,
"failed":"error ocurred",
"error": error
})
}else{
if(results.length >0){
res.send({
"code":200,
result : results
});
}
else{
res.send({
"code":204,
"success":"Record insertion Failed!"
});
}
}
});
}
I don't figured out what's the issue in this code, I appreciate if you could help me, Cheers!!
There are parameters passed for the query [articleid, userid], yet no parameters appear in the SQL. Replace the concatenation in the SQL with question marks.
var sql = `INSERT INTO deletearticles_log (articleid, userid) VALUES (?, ?)`;

Error inserting into users table in Node.js

I got the Failed to load resource: the server responded with a status of 500 (Internal Server Error)
in the // Error inserting into users table section.
What causes this problem? Where should I check? My database has all the mandatory fields. I am using SQL db.
function registerUser(rBody) {
const connection = mysqlConnection
return new Promise((resolve, reject) => {
// First attempt to has user password, and continue on success
bcrypt.hash(rBody.password, 10, (err, hash) => {
if (err) {
// Error crypting password
resolve({
success: false,
error: 'Error hashing password'
})
} else {
// Build query & insert into users table
const valuesStr = `(null, "${rBody.email}", "${rBody.firstName}", "${rBody.lastName}", "${hash}", null, 2)`
const queryString = `INSERT INTO users values${valuesStr}`
connection.query(queryString, (err, resp) => {
if (err) {
// Error inserting into users table
resolve({
success: false,
error: err
})
} else {
// User succesfully created
resolve({
success: true,
message: 'User succesfully created',
id: resp.insertId
})
}
})
}
})
})
}
Edit your query to insert into the table does not seem to follow the standard syntaxis. Try
const queryString = `INSERT INTO users(name of your columns) VALUES(${valuesStr}`)

query work on MySQL Workbench but in node.js is return problem with syntax

I need some help, When i make this query in workbench its work fine
INSERT INTO reports(creatorUserID,currentUserEditorID,companyID,stageID,scenarioID,typeID,year) VALUES (1,1,456545,1,1,1,1500);
INSERT INTO reports_tax_data(reportID,data) VALUES (LAST_INSERT_ID(),'work perfect');
but when i do the same things in nodejs
const createNewReport = () => {
return new Promise((resolve, reject) => {
connection.query(
`INSERT INTO reports(creatorUserID,currentUserEditorID,companyID,stageID,scenarioID,typeID,year) VALUES (1,1,456545,1,1,1,1500);
INSERT INTO reports_tax_data(reportID,data) VALUES (LAST_INSERT_ID(),'work perfect');`,
(err, result) => {
if (err) reject(err);
resolve(result);
}
);
});
};
i get this error:
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 \'INSERT INTO reports_tax_data(reportID,data) VALUES (LAST_INSERT_ID(),\'work perfe\' at line 2',
sqlState: '42000',
index: 0,
sql:
'INSERT INTO reports(creatorUserID,currentUserEditorID,companyID,stageID,scenarioID,typeID,year) VALUES (1,1,456545,1,1,1,1500);\n INSERT INTO reports_tax_data(reportID,data) VALUES (LAST_INSERT_ID(),\'work perfect\');' }
But when i make a normal select its work in nodejs
I would assume here that the Node SQL API you are using does not allow more than one statement to be executed per call (this is certainly the case for a few other programming languages). Try making separate calls for each insert:
connection.query(
`INSERT INTO reports(creatorUserID,currentUserEditorID,companyID,stageID,scenarioID,typeID,year) VALUES (1,1,456545,1,1,1,1500)`,
(err, result) => {
if (err) reject(err);
resolve(result);
}
);
And do the same for the reports_tax_data table insert.
i think you have to set a below mention configuration to allow multiple queries on node js.
var connection = mysql.createConnection({multipleStatements: true});
please check and comment if any issue.

INSERTING into custom mysql database table

I am currently trying to insert data into a specific table name that is saved to a variable but I keep on receiving a ER_PARSE_ERROR whenever I try executing it.
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 ''Test' SET `date` = '201
9-05-07', `league` = '1', `matchup` = '1'' at line 1
Here my what the post request looks like
app.post('/addData', function(req, res) {
var id = req.body.id
var data = {
date: req.body.date,
league: req.body.league,
matchup: req.body.matchup,
}
con.query('INSERT INTO ? SET ?', [id, data], function(err, resp) {
if (err) throw err;
res.redirect('back');
});
});
It seems like from the error message, there are additional quotes around Test when passed into the query but when doing console.log(id), it just prints out Test without the quotes.
app.post('/addData', function (req, res) {
var data = {
id: req.body.id,
date: req.body.date,
league: req.body.league,
matchup: req.body.matchup,
};
con.query('INSERT INTO Test SET ?', data, function (err, resp) {
if (err) throw err;
res.redirect('back');
});
});
Can you try this?
// This is the best ES6 way you can try out make some changes in your date format.
app.post('/addData', async (req, res) => {
var data = {
id: req.body.id,
date: req.body.date,
league: req.body.league,
matchup: req.body.matchup,
};
await con.query('INSERT INTO Test SET ?', data, (err, resp) => {
if (err) throw err;
res.redirect('back');
});
});