Mursil
Mursil

Reputation: 47

How to insert data into MySQL table using Node and express?

I am using Node with express and MySQL for database. I have created an ejs file wherein I have a form (method=POST)

In my server file, I can retrieve the data send by that form, I can even console.log it and get the desired output. Since there are multiple entries in the form, I am using different variables to store those entries in my server file.

In the query, when I am passing those variables to insert into the database, the database only inserts Null, instead of the actual data stored in the variable.

The code for the form is given below:

    <form action="/newuser" style="border:1px solid #ccc" method="post">
  <div class="container">
    <h1>Sign Up</h1>
    <p>Please fill in this form to create an account.</p>
    <hr>

    <label for="Name"><b>Name</b></label>
    <input type="text" placeholder="Enter Name" name="name" required>

    <label for="email"><b>Email</b></label>
    <input type="text" placeholder="Enter Email" name="email" required>


    <label for="psw"><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="psw" required>

    <hr>

    <label for="address"><b>Address</b></label>
    <input type="text" placeholder="House no and Street" name="address" required>


    <label for="city"><b>City</b></label>
    <input type="text" placeholder="Enter City" name="city" required>

    <label for="pin"><b>Postal Code</b></label>
    <input type="number" placeholder="Enter pin" name="pin" required>

    <label for="country"><b>Country</b></label>
    <input type="text" placeholder="Enter Country" name="country" required>

    <label for="mobile"><b>Mobile Number</b></label>
    <input type="number" placeholder="Enter Mobile Number" name="mobile" required>




    <div class="clearfix">

     <a href="/"><button type="button" class="cancelbtn">Cancel</button></a>
      <button type="submit" class="signupbtn">Sign Up</button>
    </div>
  </div>
</form>

The code on the server file is given below:

 var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var mysql = require('mysql');

app.use( express.static( "public" ) );
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 


var connection = mysql.createConnection({
    host: "localhost",
    user:"root",
    password:"",
    database:"bakery"
});


//some more code to get different routes

connection.connect(function(error){
    if(error){
        console.log("Error while connecting to database")
    }
    else{

        // console.log("connected");
 connection.query("SELECT * FROM products", function (err, result, fields) {
    if (err) throw err;
        for (var i = 0; i < result.length; i++) {
       var row = result[i];
       console.log(row.ProductName, "costs", row.Price, "and its from category", row.Category  );
}   
    // console.log(result);
    })
}});


app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");

app.post("/newuser", function(req, res) {
    // get data from forms and add to the table called user..

    var name = req.body.name;
    var email = req.body.email;
    var password = req.body.psw;
    var city = req.body.city;
    var address = req.body.address;
    var country= req.body.country
    var pin = req.body.pin;
    var mobile = req.body.mobile;

    console.log(name, mobile, pin);

    connection.query("INSERT INTO user (Name, Email, Address, City, Country, password) VALUES", (name , email, address, city, country , password), function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
  });
    res.redirect("/");

Using this code, it only inserts Null into the database no matter what I type in the form.

Upvotes: 3

Views: 22405

Answers (3)

tMan44wiz
tMan44wiz

Reputation: 146

I think the issue is from your Query syntax. I restructured your code to the one below. I hope it will solve the problem.

app.post("/newuser", function(req, res) {
    // get data from forms and add to the table called user..

    var reqBody = req.body;

    const name = reqBody.name;
    const email = reqBody.email;
    const password = reqBody.psw;
    const city = reqBody.city;
    const address = reqBody.address;
    const country= reqBody.country
    const pin = reqBody.pin;
    const mobile = reqBody.mobile;

    const queryString = `INSERT INTO user (Name, Email, Address, City, Country, password) VALUES ('"+name+"', '"+email+"', '"+address+"', '"+city+"', '"+country+"', '"+password+"')`;

    connection.query(queryString, function (err, result) {
    if (err) {
        // Throw your error output here.
        console.log("An error occurred.");
    } else {
        // Throw a success message here.
        console.log("1 record successfully inserted into db");
    }
  });

Upvotes: 1

Joe Powell
Joe Powell

Reputation: 1

    let name = req.body.name;
    let email = req.body.email;
    let password = req.body.psw;

     const sql = `INSERT INTO user (name, email, password)
       VALUES ('${name}','${email}', '${password}')`;
         db.query(sql, (err, res)=> {
         if(err) throw err;
      })

Upvotes: 0

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

Try like this:

var sql = `INSERT INTO user 
            (
                Name, Email, Address, City, Country, password
            )
            VALUES
            (
                ?, ?, ?, ?, ?, ?
            )`;
connection.query(sql, [name , email, address, city, country , password], function (err, data) {
    if (err) {
        // some error occured
    } else {
        // successfully inserted into db
    }
});

Upvotes: 9

Related Questions