Inserting Form Data into MySQL Database When Using Nodejs Express

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

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
}
});

Sending data in a html form to mysql data base using express results in undefined database columns

You're using express.json() but your form data is not in JSON format.

You can install express-formidable with npm in your app folder

Then you need to create the middleware using it, like so:

// in app.js
const formidableMiddleware = require('express-formidable');
//...

// Note that req.fields will be instead of req.body due to middleware
// used to handle json, forms, and uploading files
app.use(formidableMiddleware(
{
encoding: 'utf-8',
// means multi files (array of files) in one request
multiples: true,
}
));

You will need to replace app.use(express.json()); with above snippet

You can also check an example from ExpressJS repo on github for multipart forms

Posting Form data to MySQL using nodejs w/ Express

It should be this,

app.post('/data', function(req, res){
var username=req.body.name;
connection.query("INSERT INTO `names` (name) VALUES (?)", username.toString(), function(err, result){
if(err) throw err;
console.log("1 record inserted");
});
res.send(username);
});


Related Topics



Leave a reply



Submit