Reputation: 171
I created this code to insert data to database using nodejs and mysql and that's worked and the data inserted but the problem the page still reloaded and never stop after i clicking on submit button and sending the same value more than one time to the database
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
bodyParser = require('body-parser');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
database: 'chmult',
user: 'root',
password: '',
});
users = [];
connections = [];
app.get('/', function(req, res){
res.sendFile(__dirname + '/');
});
app.use(bodyParser.urlencoded({
extended: true
}));
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
connection.connect();
app.post("/", function (req, res) {
console.log(req.body.user.username)
connection.query("Insert into tesko (username) VALUES ('"+req.body.user.username+"')")
});
app.listen(3231);
console.log('Example app listening at port:3000');
the html code
<html>
<form method="post" action="">
<input type="text" name="user[username]">
<input type="submit" value="Submit">
</form>
</html>
Upvotes: 1
Views: 647
Reputation: 38509
You've missed the callback on connection.query
and you don't do anything with res
Try this
app.post("/", function (req, res) {
console.log(req.body.user.username)
connection.query("INSERT INTO tesko (username) VALUES ('"+req.body.user.username+"')", function(err){
return res.send('Done');
})
});
See here:
https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp
As noted in comment of question, this is ripe for SQL injection, and you should use parameters instead:
app.post("/", function (req, res) {
console.log(req.body.user.username)
connection.query("INSERT INTO tesko SET ? ", {username: req.body.username}, function(err){
return res.send('Done');
})
});
Upvotes: 2