使用node.js将数据从html表单发送到mysql表

时间:2018-04-13 21:31:32

标签: mysql node.js html-form

我正在尝试将数据从我的表单发送到mysql数据库。我的表有三列减去id列 这是表单的html:

<!DOCTYPE html>
<html lang="en">
    <head>
        
        <title>contact form</title>

    </head>
    <body>
        <div id="page">
            <form method="post" action="/myaction">
                <label for="name">Enter name: </label>
                <input id="name" type="text" name="name" value="<%= qs.person %>"> <br><br>
    
                <label for="age">Enter age: </label>
                <input id="age" type="number" name="age" value="<%= qs.year %>"><br><br>
                
                <label for="department">Enter department: </label>
                <input id="dept" type="text" name="department" value="<%= qs.dept %>"><br><br>
                
                <input type="submit" value="OK">
            </form>
    
            <!--site javascript included-->
            <script src="jquery-3.2.0.min.js"></script>
            <script src="js/bootstrap.min.js"></script>
            <script type="text/javascript" src="site.js"></script>
        </div>
    </body>
</html>

这是我的node.js代码,app.js:

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

var app = express();
app.set('view engine', 'ejs');

var urlencodedParser = bodyParser.urlencoded({ extended: false });

var con = mysql.createConnection({
    host: "localhost",
    user: "Elijah",
    password: "chemistry96",
    database: "mydb"
});


app.get('/contact', function (req, res) {
    res.render('contact', { qs: req.query });
});

app.post('/myaction', urlencodedParser, function (req, res) {
    console.log(req.body);
    var name = req.body.name;
    var age = req.body.age;
    var department = req.body.department;

    con.connect(function (err) {
        if (err) throw err;
        console.log("connected");

        var sql = "INSERT INTO 'customers' (name, age, department) VALUES (name, age, department)";
        con.query(sql, function (err) {
            if (err) throw err;
            console.log("One record inserted");
        });
    });
    res.render('contact-success', { data: req.body });
});

app.listen(3000, function () {
    console.log('server running on port 3000');
});

当我在表单中输入一些值并运行它时,我收到此错误:

错误:ER_PARSE_ERROR:您的SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以便在''customers'附近使用正确的语法(名称,年龄, 部门)第1行的价值(名称,年龄,部门)

我发现很难搞清楚。请帮忙!!!

1 个答案:

答案 0 :(得分:1)

您不应在表名周围添加引号。 检查this