nodejs接收表单写入mysql,使用带有Express的Node.js将表单数据发布到MySQL

I am trying to write a simple server.js in Node, that posts form data from my html file, into MySQL. But I am getting a Syntax error. I will post the code and error below. I'm struggling to resolve this issue.

Learning Node Server

Learning Node and JS

With Ninad

Enter your name in the database

var express = require('express');

var app = express();

var mysql = require('mysql');

var bodyParser = require('body-parser');

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({extended: false}));

//app.use(express.json());

//app.use(express.urlencoded());

//app.use(app.router);

app.use(express.static('public'));

var connection = mysql.createConnection({

host : 'localhost',

user : 'root',

password : '3748',

database : 'nodedb'

});

connection.connect();

app.get('/', function (req, res) {

res.sendFile(__dirname + '/node.html');

});

app.post('/data', function(req, res){

var username=req.body.name;

connection.query("INSERT INTO `names` (name) SET ?", username.toString(), function(err, result){

if(err) throw err;

console.log("1 record inserted");

});

res.send(username);

});

//connection.end();

app.listen(3000, function () {

console.log('Example app listening on port 3000');

});

If I entered yahoo2 as the name, this is the error I get-

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET 'yahoo2'' at line 1

at Query.Sequence._packetToError (/home/ninad/node-workspace/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)

解决方案

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

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值