I have a problem I need help with a question. So the problem is I have a route to display all rows of my students table and it works, but know when I try the code below to search for a specific student_id I get:
"Failed to query for users: Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'where clause'"
I have tried the queryString as:
My table has student_id, firstName, lastName, checkIn, and checkOut as columns.
They are all VARCHARS.
queryString = SELECT * FROM students WHERE student_id = ${id}
queryString = SELECT * FROM students WHERE student_id = ? and then getConnection().query(queryString, [id], (err, rows, fields) => {
But I get the same error, I would really appreciate the help.
The question that I have would be implementing after all my different search routes work as intended to display the data nicely in html, but I'm new to this and I can't find anything to help me with this problem. I would like it to display as a list almost like MySQL displays it. Is that possible? I'm using the ejs view engine as my html pages.
// Route to search by id
router.get("/searchById", (req, res) => {
const id = req.body.id
queryString = `SELECT * FROM students WHERE student_id = ${id}`
getConnection().query(queryString, (err, rows, fields) => {
// If error occures
if(err) {
console.log("Failed to query for users: " + err)
res.sendStatus(500)
return
}
if(rows) {
console.log(rows)
console.log("We fetched Students successfully")
res.json(rows)
}
})
})
For GET request you should use req.query.id
For post request you should use req.body.id
In your code you have used get request and tried to fetch req.body.id
Related
I'm working on a react registration form which contain some fields (idStudent(primary key & auto increment), first name, last name, ....., faculty, prerequisites), I'm using Formik & yup for validation.
Later on, I have to link my app with a recommendation system (recommend a final year project to students) based on prerequisites and the obtained grades in some subjects.
At first, I used just one table to store the data coming from the form in frontend,
student(firstname, lastname, ... ,prerequisites)
A student can select prerequisites from a react select that contain prerequisites according to the faculty (example : if a student study computer science, the react select will show only computer science prerequisites like react, angular, machine-learning ....).
Taking into consideration a student can have multiple prerequisites, so the prerequisites column in students table will contain multiple id's of the selected prerequisites,
The prerequisites are stored in an other table in my database ( prerequisites(idFaculty, idPrerequisites, prerequisite) )
I know that I can store multiple id's in one column using a JSON file but after some researches here on Stackoverflow in some previous posts, I found that it's difficult to deal with JSON especially if I want to update a column.
So I created another table to store the selected prerequisites by a student when registering
(studentPrerequisites(idStd (foreign key reference to idStudent from students table), idPrerequisite(foreign key reference to idPrerequisites from Prerequisites table))
The problem I'm facing is how to send two post's requests via axios, taking into
consideration that maybe I should use a loop to store multiple rows in case a student select multiple Prerequisites.
This is what I did :
My backend file
app.post("/registerStudent", (req, res) => {
const faculty = req.body.faculty;
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const phone = req.body.phone;
const email = req.body.email;
const password = req.body.password;
db.query(
"INSERT INTO students (email, password, firstName, lastName, faculty, phone) VALUES (?,?,?,?,?,?)",
[email, password, firstName, lastName, filiere, phone],
(err, result) => {
if (err) {
console.log(err);
} else {
// store chosen prerequisites
//result.insertId is the current idStudent of the student who registering
const idStd = result.insertId;
const idPrerequisite = req.body.idprerequis;
db.query(
"INSERT INTO studentPrerequisites (idStd, idPrerequisite) VALUES (?,?)",
[idFiliere, idPrerequisite],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
);
}
}
);
});
My frontend code
const onSubmit = (values, actions) => {
Axios.post("http://localhost:3001/registerStudent", {
faculty: values.faculty,
firstName: values.firstName,
lastName: values.lastName,
phone: values.phone,
email: values.email,
password: values.password,
})
.then(() => {
//preId is an array that contains the selected prerequisites(id's) from react select
//I try to use a for loop to store multiple of prerequisites dynamically in case a
//student select multiple prerequisites
for (let i = 0; i < preId.length; i++) {
idPrerequisites: preId[i],
}
})
.then(() => {
console.log("success!");
});
actions.resetForm();
};
It might be best to let the backend handle multiple prereqs by passing in an array of prereqs to your request. I'd also use Knex and async/await to avoid a lot of .then chaining and to make use of transactions. Transactions will revert all queries if any errors occur within the transaction. Knex also makes querying databases super easy with built-in methods instead of writing raw SQL. You should also be using object destructuring instead of doing firstName = req.body.firstName, lastName = req.body.lastName, etc. You can learn more about knex and getting your db connected to it here: https://knexjs.org/guide/#node-js
Also, WHY ARE YOU NOT HASHING YOUR PASSWORDS? That is the most basic security you should be doing at a minimum!
I'm having trouble sending a secure SQL query to mysql server from nodeJS.
When using this piece of code:
let test = "chart1yusd"
db.query('SELECT '+ test +' FROM coinDetail WHERE id = ?',[
requestID,
],function(err, result){
console.log(result)
res.send(result);
});
I get the correct output:
[ RowDataPacket {
chart1yusd:
'[[1589846400000,0.118103090573034],[1590710400000,0.14990946026516133],[1591574400000,0.13832947332698067],[1592438400000,0.14626382998803866],[1593302400000,0.12312689681792738],[1594166400000,0.13064585929472963],[1595030400000,0.15134667446052835],[1595894400000,0.14511870584962466],[1596758400000,0.2044381065518002],[1597622400000,0.27718349745013865],[1598486400000,0.24733539468353966],[1599350400000,0.15428765583919232],[1600214400000,0.18333082011361068],[1601078400000,0.16554945200142196],[1601942400000,0.15536379703562367],[1602806400000,0.17817122591867382],[1603670400000,0.14901182983793498],[1604534400000,0.15243756831164262],[1605398400000,0.25106271236512906],[1606262400000,0.22676917209412703],[1607126400000,0.22559988488004115],[1607990400000,0.3198349358258863],[1608854400000,0.28175278764129286],[1609718400000,0.48270197854575086],[1610582400000,0.5562085890730089],[1611446400000,0.4835010798224596],[1612310400000,0.46142579899847125],[1613174400000,0.7327130188547617],[1614038400000,0.7803392989162374],[1614902400000,1.2216997730172996],[1615766400000,1.1508817751759253],[1616630400000,1.2024881678362118],[1617494400000,1.1159947150076852],[1618358400000,2.3093588705698713],[1619222400000,1.9654124655802336],[1620086400000,2.0674879115219373],[1621230497000,1.3424936470400413]]' } ]
But when using this piece of code (the more secure version against sql injection):
let test = "chart1yusd"
db.query('SELECT ? FROM coinDetail WHERE id = ?',[
test, requestID,
],function(err, result){
console.log(result)
res.send(result);
});
I get this output, and not the data I want like before.
[ RowDataPacket { chart1yusd: 'chart1yusd' } ]
What did I do wrong and how can I fix this?
The query SELECT ? FROM coinDetail WHERE id = ? is not a valid MySQL prepared statement, because only literal values can be represented by ? placeholders. Database objects, including column and table names, can't have placeholders.
So, you are basically stuck using your first version. If you know a priori that the chart1yusd column is what you want to select, then just hard code it:
SELECT chart1yusd FROM coinDetail WHERE id = ?
You cannot use placeholders for columns, only for values. To dynamically select the column of interest, just select all columns, and then pick the one you need:
let test = "chart1yusd"
db.query('SELECT * FROM coinDetail WHERE id = ?', [
requestID,
], function(err, result){
console.log(result[0][test])
res.send(result[0][test]);
});
I have been trying to setup my Nodejs MySQL database configuration. I found this passport.js config for MySQL on Github. The config works properly but there is a part that I do not understand.
var insertQuery = "INSERT INTO users ( email, password ) values ('" + email +"','"+ password +"')";
console.log(insertQuery);
connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
I am confused about the insertID field. The table I am using does not have a field called insertID. It does however have a field named ID. I tried changing that line to
newUserMysql.id = rows.Id;
bu doing so gives me:
Error: Failed to serialize user into session
Leaving it as it is gives me no error
Looks like insertID has nothing to do with the ID field of my table but I do not understand what it means
That probably represents LAST_INSERT_ID() which is the ID of the last row inserted.
The response of an INSERT is not "rows" but a result object, so maybe better named it'd be:
connection.query("...", function(err, result) {
newUserMysql.id = result.insertId;
return done(null, newUserMysql);
});
It's important to note that using Promises dramatically simplifies your code, and async/await can take that even further. This could be as simple as:
let result = await connection.query("...");
newUserMysql.id = result.insertId;
return newUserMysql;
Where that's inside an async function with a Promise-driven database library like Sequelize. You're not handling the potential errors in your first case. In the second you'll get exceptions which will wake you up when there's problems.
I am new developer ReactJS, I develop a table with ReactJS on the FrontEnd, NodeJS on BackEnd and MySQL about the database.
I want when I click on the view button on Action column, it will be redirected to another page, which display a list containing the result of the Select query, as below :
My router :
exports.viewclient = function(req, res) {
var Code = req.query.Code;
console.log(req.query.Code);
connection.query('SELECT Code, Prenom, Nom, FAX, Telephone, Email, Adresse1, Adresse2 FROM clients WHERE Code = ?',[Code], function(error, results, fields) {
if (error) throw error;
res.send(JSON.stringify(results));
console.log(results);
});
}
My server :
router.get('/viewclient/:Code', clients.viewclient);
When, I test the backend with Postman, http://localhost:4000/app/viewclient/:Code=1111 , it returns : [] and console.log(req.query.Code) returns undefined
How to fix that please ?
Need a couple of changes in your URL and code
The URL should be http://localhost:4000/app/viewclient/111
In your controller
console.log(req.params);
Output
{ "Code": "111"}
After adding a product to the mysql database, I want to dump all the products with the latest product. This product is being added with an algorithm to the database and I want to list all the products immediately afterwards. Already tried "async", "promise" etc.
--When the table is empty--
connection.query("INSERT INTO `products` (id, name, price)", function (error, results, fields) {}); //inserted one row
connection.query("SELECT * FROM `products`", function (error, results, fields) {}); // show only []
after second insertion list query show only first row but not second. The main problem is this and table has two rows.
Thank you.
Query data when insert is done:
connection.query("INSERT INTO `products` (id, name, price)",
function (error, results, fields) {
connection.query("SELECT * FROM `products`", function (error2, results2, fields2){});
});
connection.query("INSERT INTO products(id, name, price)",
function (error, results, fields) {
if(error) return ....
else{
connection.query("SELECT * FROM products", function
(error,results,fields2){
var returned_data = results;
console.log(results);
//res.send(results);
})
}});
Would be the way to go, but check whether you're inserting the data the right way at all, since you haven't provided the way you do it, I doubt that any async method would fail you itself.
EDIT on request: You can pass the results to a variable, but you can only use it inside that function if you don't (because of its scope) , ie res.send or res.end it (if you're using this inside a request, which I'm guessing you are), or console.log it or just write it to a file.