How to make more than query in the same axios in Node js?
Several remarks about your code:
- The assignment
SSN = result
happens asynchronously, after the first database query is completed, but you want to use the value ofSSN
in the INSERT statement, which is executed synchronously. In other words: The first query is sent, then the second query is sent, then the INSERT statement is sent, all synchronously. Only later do the responses for the two queries come in, asynchronously. That's when the(err, result) => ...
functions are executed. SoSSN
receives its value after it has been used. -
result
does not contain the SSN value directly. According to themysql
documentation, you must writeSSN = result[0].SSN;
- Your second query
const ID = db.query(...)
uses a different form, without the(err, result) => ...
callback function. In this form, it returns a promise, not the section ID that you expect. - You create the SQL queries through string operations, which exposes your database to the risk of SQL injection. Use placeholders (
?
) instead. - How is the database field
sectionname.ID
filled during the insert operation? - Can you be sure that the
FullName
andSectionName
are unique in their database tables?
Assuming they are unique and the sectionname.ID
is generated by the database automatically, you can perform the insertion with a single SQL statement:
db.query(`INSERT INTO section(TeacherSSN, SectionNameID)
SELECT user.SSN as TeacherSSN, sectionname.ID as SectionNameID
FROM user, sectionname
WHERE user.FullName = ?
AND section.SectionName = ?`,
[req.body.TeacherName, req.body.SectionName],
(err, result) => ...);
This obviates the need to wait for the result of a query before you make an insertion.