Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  52] [ 1]  / answers: 1 / hits: 20077  / 7 Years ago, sat, august 26, 2017, 12:00:00

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.







<head>

<title>Learning Node Server</title>
<link rel=stylesheet href=style.css />

</head>


<body>

<div class=header>
<h1>Learning Node and JS</h1>
<p>With Ninad</p>
</div>

<form action=/data method=post>
<label for=name>Enter your name in the database</label>
<input type=text name=name>
<input type=submit value=submit />
</form>


<div class=container></div>

<script type=text/javascript src=main.js></script>

</body>




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)


More From » mysql

 Answers
9

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

[#56654] Tuesday, August 22, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wilson

Total Points: 27
Total Questions: 93
Total Answers: 93

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
wilson questions
Tue, Aug 9, 22, 00:00, 2 Years ago
Wed, May 11, 22, 00:00, 2 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Wed, May 13, 20, 00:00, 4 Years ago
;