Elijah Arhinful
Elijah Arhinful

Reputation: 21

Sending data from html form to mysql table using node.js

I am trying to send data from my form to mysql database. My table has three columns minus the id column This is the html for the form:

<!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>

this is my node.js code, 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: "Name",
    password: "XXXXXXXXXXXX",
    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');
});

When I enter some values into my form and run it, I get this error:

Error: ER_PARSE_ERROR: 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 ''customers' (name, age, department) VALUES (name, age, department)' at line 1

I'm finding it difficult to figure it out. Any help please!!!

Upvotes: 0

Views: 4020

Answers (1)

Snehal
Snehal

Reputation: 35

You should not add quotes around the table name. Check on this.

Upvotes: 1

Related Questions