'Condition with mysql request
I have a problem for my image (I use multer), when in my user edit form. Is it possible to put conditions on my image if the field is null, it still sends my request to the server. I did the necessary on the front-end to send the firstname and lastname data but for the image impossible, that's why I want to go through the back end.
exports.updateUser = (req, res, next) => {
try {
if (res.locals.userId === parseInt(req.params.id)) {
const user = [
[req.body.user_lastName],
[req.body.user_firstName],
[`${req.protocol}://${req.get('host')}/images/${req.file.filename}`],
[req.params.id]
]
const sql = "UPDATE users SET user_lastName=?, user_firstName=?,user_avatar=? WHERE user_id=?";
db.query(sql, user, function (error, results) {
if (!error) {
res.status(200).json({ message: 'modification profil executé' });
} else {
console.log(error)
res.status(401).json({ error: 'Erreur utilisateur table users' });
}
});
} else {
res.status(401).json({ error: 'erreur d\'authentification, vous n\'avez pas les droits pour modifier ce profil' })
}
} catch (error) {
res.status(500).json({ error });
console.log(error)
}
}
Solution 1:[1]
Use an if statement to set a variable conditional on whether the field was provided.
exports.updateUser = (req, res, next) => {
try {
let image = null;
if (req.?file.?filename) {
image = `${req.protocol}://${req.get('host')}/images/${req.file.filename}`;
}
if (res.locals.userId === parseInt(req.params.id)) {
const user = [
req.body.user_lastName,
req.body.user_firstName,
image,
req.params.id
]
const sql = "UPDATE users SET user_lastName=?, user_firstName=?,user_avatar=? WHERE user_id=?";
db.query(sql, user, function(error, results) {
if (!error) {
res.status(200).json({
message: 'modification profil executé'
});
} else {
console.log(error)
res.status(401).json({
error: 'Erreur utilisateur table users'
});
}
});
} else {
res.status(401).json({
error: 'erreur d\'authentification, vous n\'avez pas les droits pour modifier ce profil'
})
}
} catch (error) {
res.status(500).json({
error
});
console.log(error)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
