How should I insert data to MYSQL database from a HTML form?


I know that node runs on the backend and while it’s not a problem to connect to the SQL database via the server.js file, I cannot understand how I could do that from within a js linked to a form element (that’s definitely client-side js, and I cannot make the connection from inside there). I know this maybe confusing, so I would very grateful for any help.
I am a beginner, so please keep it simple. Youtube videos are also fine. Thanks in advance 🙂

    const mysql = require("mysql");
    //create connection to sql database
    const connection = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "",  
        database: "blog",

      connection.query('select * from posts', () => {
//this works when i put it inside server.js (using express) but not inside some other file- says cannot use require.


Plain and simple , this is the initialization of the database connection. In order to use this connection object in other files you need to export it or to incorporate it in "req" object supported by express. I suggest that in the end of the file you add

module.exports ={
     connection : mysql.createConnection(config) 

and then use the connection object to make queries elsewhere.
Apart from this i would suggest that you start using Sequelize since it is a powerful ORM for nodejs. First learn sql logic and test your queries directly in the database through Mysql workbench , pgadmin , etc and then dive deep into sequelize documentation to take yourself to the next level. Hope this answer will solve your problem!

Answered By – Devis Arapi

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.