I'm working on an EC2 server and I need to insert some data into a mySql table from server-side.
I have verified that the information in the request body is accurate via logging their values to the console i.e. console.log(req.body.name). I also know that my table exists.
My connection pool is defined at the top of the page:
var pool = mysql.createPool({
host: 'localhost',
user:'student',
password: 'default',
database: 'workouts'
});
My insert inside of a POST function is:
pool.query("INSERT INTO workouts(`name`, `reps`, `weight`, `date`, `lbs`) VALUES (?, ?, ?, ?, ?)", [req.body.name, req.body.reps, req.body.weight, req.body.date, req.body.lbs],
function(err, result){
if(err){
console.log(err);
return;
}
});
});
My table was created using professor-supplied code:
app.get('/reset-table',function(req,res,next){
var context = {};
pool.query("DROP TABLE IF EXISTS workouts", function(err){ //replace your connection pool with the your variable containing the connection pool
var createString = "CREATE TABLE workouts("+
"id INT PRIMARY KEY AUTO_INCREMENT,"+
"name VARCHAR(255) NOT NULL,"+
"reps INT,"+
"weight INT,"+
"date DATE,"+
"lbs BOOLEAN)";
pool.query(createString, function(err){
context.results = "Table reset";
res.render('home',context);
})
});
});
Related
I'm a beginner in general and trying to use MySQL with nodeJS to be able to integrate projects in WordPress.
app.post('/users/add', (req, res) => {
id = req.body.id, firstname = req.body.firstname, surname =
req.body.surname
let sql = "INSERT INTO `users_tbl` VALUES (id, firstname, surname)";
db.query(sql, [id, firstname, surname],
(err, rows, fields) => {
if(!err)
res.send("User successfully added");
else
console.log(err);
});
})
With the given code I can add through Postman an entry, but an empty one.
I already tried to assign my values to the keys after VALUES, but maybe my syntax was wrong
Assuming you are using this module.
db.query(sql, [id, firstname, surname]
Here you are passing variables into your query for them to replace placeholder values.
let sql = "INSERT INTO `users_tbl` VALUES (id, firstname, surname)";
But here you have just put column names instead of placeholder markers.
Change that to:
let sql = "INSERT INTO `users_tbl` VALUES (?, ?, ?)";
Aside: You should probably have the id field be an auto-increment field and not a user-submitted value.
app.post('/users/add', (req, res) => {
id = req.body.id,
firstname = req.body.firstname,
surname = req.body.surname
let sql = "INSERT INTO `users_tbl` (id, firstname, surname) VALUES
(?,?,?)";
db.query(sql, [id, firstname, surname], (err, rows, fields) => {
if(!err)
res.send("User successfully added");
else
console.log(err);
});
});
Try this code just replace your values with ? and run postman again.
Add a breakpoint or use console.log to check if you are actually getting the body fields in req.body.
Try setting 'Content-Type' as application/json in headers while sending the request through postman and send raw json in body.
I'm trying to make something like console.log('Dear user, there was updates'). I made basic console.log for now which is not what I'm looking for because I want from node to check if there was some update on database, not updating in function.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
});
con.connect(function(err) {
if (err) throw err;
//Update the address field:
var sql = "UPDATE users SET name = 'lol2' WHERE name = 'lol'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
edit: alert to console.log
Alert wont work in Node.js Instead sent a response back to client side with the total affected of results. And based results, show alert with the count received.
eg.
return res.status(200).return(result.affectedRows);
and in client side
if(datareceived > 0){
alert(`Dear user, there was ${datareceived} price updates moment ago`)
}else{ // your other logic }
I am having trouble returning results when running queries on my MySQL database using Node.js. Below is an example of my code, which currently outputs nothing to the console.
const mysql = require("mysql");
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'tl'
});
connection.connect();
connection.query = ('SELECT * from employees', function(error, results, fields) {
if (!error) {
console.log(results);
} else {
throw error;
}
});
connection.end();
Authentication is correct.
The database and table are not empty. Running the same query in MySQL itself returns rows.
The code below will give me 'Connection established':
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
There is nothing wrong with my DB or table, all is working as expected, apart from running these queries. I've followed the official documentation and others
This is my current javascript.
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'codify',
port: '8889'
})
connection.connect();
//var querydata = +"'"+data.RegUsername + "','"+data.RegPassword+"'"
connection.query("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES ?", data.RegUsername,+","+ data.Regpassword , function(err,rows,fields){
if (err) throw err;
})
});*/
This query causes an error, what am I doing wrong?
What you're doing wrong is that you're trying to concatenate your two values into a single string and have that string substituted into your single ?. If you're using a single ?, you need to pass in an object where the object's parameters are the same as the database field names.
I'd do it like this:
let payload = {
UsernameDB: data.RegUsername,
PasswordDB: data.Regpassword
};
connection.query("INSERT INTO Codify SET ?", payload, function(err, rows) {
});
You can also do it like this with an array instead of an object:
let sql = "INSERT INTO Codify (UsernameDB, PasswordDB) VALUES (?, ?)";
connection.query(sql, [ data.RegUsername, data.Regpassword ], function(err, rows) {
});
or like this:
let sql = "INSERT INTO Codify SET UsernameDB = ?, PasswordDB = ?";
connection.query(sql, [ data.RegUsername, data.Regpassword ], function(err, rows) {
});
But I find using a single ? along with an object is more readable.
placeholder ( ? character) will escape your querydata for avoid sql-injection. cause you don't use combined string for query. use placeholders to each inserted value. like
("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES (?,?)", [data.RegUsername,data.Regpassword] , function () )
check nodejs mysql driver document here
I am reading this and tried to connect to MYSQL database using node js.Here is my program
var mysql = require('mysql');
var connection = mysql.createConnection({
host : "localhost",
User : "root",
password: ""
});
connection.connect();
connection.query("use test");
var strQuery = "select * from chat";
connection.query( strQuery, function(err, rows){
if(err) {
throw err;
}else{
console.log( rows );
}
})
connection.destroy( );
I an not getting any error but also unable to get any output
In order to have the program wait for your queries to be executed, replace
connection.destroy();
with
connection.end();