I changed some of the names in my update query and now it no longer works ;(. I get this 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 'WHERE id = 42' at line 1",
sqlState: '42000',
index: 0,
sql: "UPDATE developers SET name = 'eyo', absent = '1', WHERE id = 42"
I changed slack_id into Name, changed everything like normal, but still doesn't work.
// UPDATE
app.put("/update", (req, res) => {
const id = req.body.id;
const name = req.body.name;
const absent = req.body.absent;
db.query("UPDATE developers SET name = ?, absent = ? WHERE id = ?" ,[name, absent, id],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
console.log(result)
}
}
);
});
This Update redirects to my Axios.put
const updateDeveloper = () => {
try {
setSuccessMessageUpdate('');
setErrorMessageUpdate('');
Axios.put(`${url}/update`, { name: name, absent: absent, id: props.id }).then(
(response) => {
return (
{
id: props.id,
name: props.name,
slack_id: props.slack_id,
absent: props.absent,
selected: props.selected,
}
)
}
);
setSuccessMessageUpdate(`successfully updated developer `);
} catch (err) {
setErrorMessageUpdate('something went wrong');
}
};
I would say the rest of the code is irrelevant because the error is clearly mentioning a database issue. Maybe its a type error? I can't see it.
Never-mind I found the issue already. Seems the code is fine but after I saved I forgot to restart node, my bad.
Related
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
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.
I am trying to throw an error in the following syntex:
if(err) throw err
What I expect is to print the log by the line of "console.log(err)" instead of app crashed.
However, this occurs an error with app crashed and says
throw err; // Rethrow non-MySQL errors
^
Error: Error: ER_DUP_ENTRY: Duplicate entry 'test4' for key 'nickname_UNIQUE'
I cannot figure out why this happens and need helps from the experties.
code :
api.post('/', (req, res) => {
const email = req.body.email
const nickname = req.body.nickname
const password = req.body.password
const thumbnail = req.file
const type = req.body.type
const hasherCallback = (err, pass, salt, hash) => {
if (err) throw err
const sql = `INSERT INTO users set ?`
const fields = { nickname, email, 'password': hash, salt, thumbnail, type }
const queryCallback = (err) => {
if (err) throw err
return res.json(messages.SUCCESS_MSG)
}
conn.query(sql, fields, queryCallback)
}
try {
return hasher({ password }, hasherCallback)
} catch (err) {
//handle errors here
console.log(err)
}
})
return api
}
//Error : Error: Error: ER_DUP_ENTRY: Duplicate entry 'test4' for key 'nickname_UNIQUE'
The throw statement throws a user-defined exception. Execution of your function will stop and nothing will be executed from this point onwards.
See this website for help on the throw keyword. Also take the time to read about the throw new Error as this might be what you need instead of throw. This link may also be of help
In terms of why the error is occurring, the MySQL error is telling you you are inserting duplicate data into your users table. The database is rejecting it because a record already exists with the nickname value of 'test4' in the table.... So you are not allowed to insert another user with the same nickname of 'test4' into the table.
Why you may ask?
This is because You have an index on the table which requires the nickname to be unique.
Two options you could use are as follows:
Add more code to you javascript telling your user that if the nickname is already taken by another user, request that they choose another nickname and retry.
Allow duplicate nicknames by removing the unique nickname requirement on the table if you want to allow the same nickname to be inserted more than once. To do this you'll need to modify the index on the table. This may be dangerous and not suitable if your other table fields don't have a value that is unique.
Good luck and happy coding.
I found that I cannot throw errors in async function so I tried using callback.
api.post('/', (req, res) => {
const email = req.body.email
const nickname = req.body.nickname
const password = req.body.password
const thumbnail = req.file
const type = req.body.type
const errorHandle = (callback) => {
const hasherCallback = (err, pass, salt, hash) => {
if (err) return callback(err)
const sql = `INSERT INTO users SET ?`
const fields = { nickname, email, 'password': hash, salt, thumbnail, type }
const queryCallback = (err) => {
if (err) return callback(err)
return res.json(messages.SUCCESS_MSG)
}
conn.query(sql, fields, queryCallback)
}
return hasher({ password }, hasherCallback)
}
return errorHandle((err) => {
//This one equals console.log({ status: 'error' message: err })
return res.status(500).json(messages.ERROR(err))
})
})
This prints log what I want instead of app crashed.
{
"status": "error",
"message": {
"code": "ER_DUP_ENTRY",
"errno": 1062,
"sqlMessage": "Duplicate entry 'test4' for key 'nickname_UNIQUE'",
"sqlState": "23000",
"index": 0,
"sql": "INSERT INTO users SET `nickname` = 'test4', `email` = 'test4#test.com', `password` = 'FXxSpPBNFfL1KGS0sWn19N191Hj0FXtnCWwMspneVIvwB5UgPBI0MjBskEnHby357j/3VKWM7ffi/5yD5CiIRyAGMWnTaStzbVX/hhD1/y91UW9b8etWpV5koKcn9QsmD9BozX1+wkve66lTNoFUHDWA0BDj4j8O7ltsD4698LQ=', `salt` = 'cu7GlOjK4drxV/SD4CBJtiW5yirc5/TpaAroCBbCQtOy4Asr8rGvTrxArXHmPH6ADTtHlXvUEEoeUD73LS654Q==', `thumbnail` = NULL, `type` = 'local'"
}
}
This is my first project using MySQL and NodeJS, I am used to Mongo, so I might be doing something stupid here. Locally everything works fine (using MySQL) but when I deploy the following code to my hosting (that uses MariaDB) only the parent query inserts into the table (leads). The other table stays empty. Another issue is I don't have access to the NodeJS logs when it is deployed, but as far as I can tell the nested queries never get called.
var mysql = require('mysql');
global.db = mysql.createPool({
host : 'localhost',
user : 'client',
password : '******',
database : 'db'
});
router.post('/', function(req, res){
const d = req.body
let subscribe = (d.subscribe ? 1 : 0)
global.db.getConnection((err, conn) => {
if (err) {
res.end(JSON.stringify(err));
} else {
let lead = [null, d.voornaam, d.achternaam, d.email, d.postcode, d.opmerkingen, d.soort, subscribe]
let sql = 'INSERT INTO leads VALUES ?';
conn.query(sql, [[lead]], (err, results) => {
if (err) {
res.end(JSON.stringify(err));
conn.release();
} else {
const lead_id = results.insertId
d.types.forEach(w => {
let wens = [null, lead_id, w.woningType, w.slaapkamers, w.prijs, w.oplevering]
let sql = 'INSERT INTO wensen VALUES ?';
conn.query(sql, [[wens]], (err, results) => {
if(err) {
res.end(JSON.stringify(err));
conn.release();
}
})
})
res.end('True');
conn.release();
}
})
}
})
});
Check syntax. Note parens:
'INSERT INTO leads VALUES (?)'
Did this fail to tell you that?
if (err) { res.end(JSON.stringify(err)); ... }
I have created a normal registration form with following fields:
name,email,dob,gender,password
i am using express.js and within post route i access it via
req.body.(param)
console.log(req.body) shows all params.
Now i have mysql table with same columns as mentioned before. If i do insert with plain strings (eg: abcs) it works i.e. value is inserted into mysql table. Also the email in form is username in db.
When I try inserting all the fields it shows error :( unknown username field ). username varchar(50) is its definition. in the logs i see password field's input is surrounded with single quotes but as for email it becomes: ('user#mail'.'com'). I also used knex, alternate ways as mentioned in mysql docs and got same error(unknown username) .
Can someone tell me how should i store email in mysql db via nodejs+express
db.js
var mysql = require('mysql');
// setup mysql
var dbcon = mysql.createConnection({
host: 'localhost',
database: 'test',
user: 'flip',
password: 'flop'
});
dbcon.connect(function (err) {
if (err) throw err;
console.log("Connected to db");
});
module.exports = dbcon;
routes/index.js:
var dbcon = require('../db');
.
.
router.post('/signup', function (req, res) {
console.log(req.body);
/* knex('users').insert( {
user_id: 1,
password: req.body.su_password,
u_firstname: req.body.su_firstname,
u_lastname: req.body.su_lastname,
u_gender: req.body.su_gender,
u_dob: req.body.su_date,
}).then(function(arg){
console.log(arg);
});
*/
dbcon.connect(function (err) {
var sqlv = {
user_id: 1,
password: req.body.su_password,
u_firstname: req.body.su_firstname,
u_lastname: req.body.su_lastname,
u_gender: req.body.su_gender,
u_dob: req.body.su_date
};
/*var sql = "insert into `users` values (?,??,??,??,??,??,??);";
var sqlv = [1,req.body.su_email, req.body.su_password, req.body.su_firstname, req.body.su_lastname, req.body.su_gender, req.body.su_date];
sql = mysql.format(sql,sqlv);
*/
//var sql ="insert into usertmp (`username`,`password`) values ('"+req.body.su_email+"','"+req.body.su_password+"');";
dbcon.query("insert into users values ? ;", sqlv, function (err, result) {
if (err) {
console.log(err);
throw err;
}
console.log("inserted into users " + result);
});
});
res.redirect('/');
});
console.log(req.body) in routes/index.js:
{ su_firstname: 'user',
su_lastname: 'virus',
su_email: 'user#mail.com',
su_gender: 'm',
su_date: '1999-01-01',
su_password: 'passowrd00' }
Error(for current example):
{ 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 'user_id = 1, password = 'passowrd00', u_firstname = 'user', u_lastname =' at line 1
Error(for insert using actual sql query with single quotes around each value):
Unhandled rejection Error: ER_BAD_FIELD_ERROR: Unknown column 'username'
in 'field list'
I figured it out !
It wasn't nodejs/expresjs mistake it was from the database.
In the database i had used triggers and forgot to use NEW/OLD prefixes.