I am trying to insert data gathered from a form filled out on my website, and storing that data in a database on phpMyAdmin.
Everything is working correctly, I am getting the message "Connected to Database." and "Records Inserted Successfully!", meaning that the communication between the website and the database is working.
However, when I check the database, there are empty records (the records are being inserted, but there are no values).
Not sure if this might help, but the parameters for the function 'db' say "unused".
var name = request.body.FirstName;
var surname = request.body.LastName;
var email = request.body.Email;
var message = request.body.Message;
console.log(name + " " + surname);
console.log(email); console.log(message);
var emailMessage = "New message from " + name + " " + surname + "(" + email + ") " + message;
function mail(emailMessage){
var nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'XXX', // add your username
pass: 'XXX' // add your password
}
});
var mailOptions = {
from: 'XXX', // add sender email (your email)
to: 'XXX', // add recipient email (maybe a friend)
subject: 'Message from Node.js app',
html: '<p>' + emailMessage + '</p>'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
mail(emailMessage);
function db(name, surname, email, message){
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'db4free.net',
user: 'XXX',
password: 'XXX',
database: 'feedback_db'
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to Database.");
var sql = "INSERT INTO messages (Name, Surname, Email, Message) VALUES (name, surname, email, message)";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("Records Inserted Successfully!");
});
}); }
db(name, surname, email, message);
response.sendFile(__dirname + '/success.html'); });
Variables aren't evaluated inside strings. When you put VALUES (name, surname, email, message) in the query, it doesn't use the variables. You should put placeholders there, and supply the values as a parameter.
var sql = "INSERT INTO messages (Name, Surname, Email, Message) VALUES (?, ?, ?, ?)";
connection.query(sql, [name, surname, email, message], function(err, result) {
if (err) throw err;
console.log("Records Inserted Successfully!");
});
I can't explain why you're getting empty records -- you should be getting an error due to the invalid values in the query.
Related
So I am trying to insert data into my database, the connection is fine, But for some reason, when I try to create the prepared statements it's not working.
All the values in my database are varchar(255) except for description which is text. The data being sent is all strings. But could that be the issue? how do I make this execute without any errors?
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const path = require('path');
const crypto = require('crypto');
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'dos-bros-it',
});
db.connect((err) => {
if(err) {
console.log(err.code);
console.log(err.fatal);
}else{
console.log("Connection has been succesfully initiated!")
}
})
const PORT = 7072;
app.use(express.static(path.join(__dirname, "client/build/")));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "client/public/", "index.html"));
});
app.post('/repair', (req, res, next) => {
$query = "INSERT INTO tickets (firstName, lastName, email, phone, description) VALUES (?, ?, ?, ?, ?)";
$data = [
[req.body.firstName],
[req.body.lastName],
[req.body.email],
[req.body.phone],
[req.body.request]
]
db.query($query,
[$data], (err, rows, fields) => {
if (!err) {
console.log('Repair was succesfully sent to the servers database! \n Records: ' + rows);
}else{
console.log(err);
}
});
console.log(req.body.firstName, req.body.lastName, req.body.email, req.body.phone, req.body.request);
res.send("<h1>FORM SENT</h1>")
next();
})
io.on("connection", (socket) => {
console.log('Client has connected to the server!!!');
socket.on('test', (msg)=>{
console.log('recieved test message!!!', msg);
})
})
http.listen(PORT, ()=>{
console.log('Server Started using port:', PORT);
})
below I have provided the error that code.
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?' at line 1",
sqlState: '42000',
index: 0,
sql: "INSERT INTO tickets (firstName, lastName, email, phone, description) VALUES ('bobby'), ('mcboba'), ('anEmail#gmail.com'), ('1234567890'), ('haww ahagor naou rngoanr ogaeo gw'), ?, ?, ?, ?, ?;"
}
Your SQL insert syntax is off. You specify 5 columns and so there should be only 5 ? placeholders. Also, what follows VALUES needs to be a tuple in parentheses (...). Use this version:
$query = "INSERT INTO tickets (firstName, lastName, email, phone, description) VALUES (?, ?, ?, ?, ?)";
I was able to figure it out, apparently it was putting all of the $data objects into just one "?", so I removed all but on "?" and it seemed to work. Hope that helps someone out in the future.
$query = "INSERT INTO tickets (firstName, lastName, email, phone, description) VALUES (?)";
$data = [
[req.body.firstName],
[req.body.lastName],
[req.body.email],
[req.body.phone],
[req.body.request]
]
db.query($query,
[$data], (err, rows, fields) => {
if (!err) {
console.log('Repair was succesfully sent to the servers database! \n Records: ' + rows);
}else{
console.log(err);
}
});
I am trying to make a log in system. Right now I am working on allowing the user to register. I am trying to make it so you can't create an account that has the same username or email as another. However, it is giving me a parse error.
Here is the code:
app.post("/create", (req, res) => {
const email = req.body.email;
const username = req.body.username;
const password = req.body.password;
db.query("SELECT email, username FROM users WHERE email = ? AND username = ?"),
[email, username],
(err, result) => {
if (err) {
console.log(err);
} else if (result) {
res.send("Username or Email is already in use.")
} else {
db.query(
"INSERT INTO users (email, username, password) VALUES (?,?,?)",
[email, username, password],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
);
}
};
});
Here is the error I am getting:
{
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "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 '? AND username = ?' at line 1",
sqlState: '42000',
index: 0,
sql: 'SELECT email, username FROM users WHERE email = ? AND username = ?'
}
I am new to StackOverflow, and to the development world. Currently learning JS and node, I am developing a personal project which will be a task management web app. I wrote the register/auth controllers for user data inserts/checks in DB (using MySQL), but ATM I am saving the password in plain text. I want to hash the password and save it in the DB, but when I go look into the table, the passed value is saved as "Object Promise", so it's not currently hashing I think. How can I correctly save the value in registration and validate it in auth? Below is the code of both auth and register controllers. Thanks.
register-controller:
var mysqlConnection = require ('../config');
const bcrypt = require ('bcrypt');
const saltRounds = 10;
module.exports.register=function(req,res){
var today = new Date();
var users={
"firstname":req.body.firstname,
"lastname" : req.body.lastname,
"email":req.body.email,
"password":bcrypt.hash(req.body.password, saltRounds),
"signup_date":today,
"last_login_date":today
}
mysqlConnection.query('SELECT count(email) as count FROM users where email = "' + req.body.email + '"', function (error, results) {
console.log(error, results[0].email);
})
mysqlConnection.query('INSERT INTO users SET ?',users, function (error, results, fields) {
console.log(error, results);
if (error) {
res.json(
error
)
}else{
console.log('User registered succesfully.');
res.redirect('/');
}
});
}
and this is auth-controller:
var mysqlConnection = require ('../config');
const bcrypt = require ('bcrypt');
module.exports.auth = function (req, res, next) {
var email = req.body.email
var password = req.body.password
console.log(email, password);
mysqlConnection.query('SELECT password FROM users where email = "' + email + '"', function (error, results) {
console.log(error, results[0]);
if (error) {
res.error = error;
}else{
if(results.length >0){
bcrypt.compare(password,results[0].password, function (err,res){
if(password === results[0].password){
console.log('User logged in succesfully.');
res.error = error;
res.user = results[0];
res.redirect('/');
}else{
res.error = error;
res.user = null;
}
}
)}
else{
res.error = error;
res.user = null;
res.redirect('/register');
}
}
next();
});
}
I have a random generated string that I set as a value for a property in my database table. On a successful update to my record I then send an email containing that same token that was used in the database record. Unfortunately the token parameter in my then statement does not contain the token and instead is replaced with a value of 1. Why is this happening and does it have something to do with how promises functionality works?
This is an example console log and SQL update that appears in my code:
This is the token: 78a4543cdd4cfd9d8c7fbad89aed9f902e07c372
Executing (default): UPDATE `user` SET `reset_password_token`='78a4543cdd4cfd9d8c7fbad89aed9f902e07c372',`reset_password_expires`='2016-04-02 14:46:13',`updatedAt`='2016-04-02 13:46:13' WHERE `email` = 'tester#gmail.com'
Then this token: 1
POST Method:
.post(function(req, res){
async.waterfall([
function(done){
crypto.randomBytes(20, function(err, buf){
var resetToken = buf.toString('hex');
done(err, resetToken);
});
}, (function(token, done){
console.log('This is the token: ' + token);
models.User.update({
resetPasswordToken: token,
resetPasswordExpires: Date.now() + 3600000
}, {
where: { email: req.body.email }
}).then(function(token, user, done){
console.log('Then this token: ' + token);
var transporter = nodemailer.createTransport(sgTransport(options));
var mailOptions = {
from: '"Test Email" <test#mywebsite.com',
to: 'tester#gmail.com',
subject: 'Password Rest Confirmation',
text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
'http://' + req.headers.host + '/reset/' + token + '\n\n' +
'If you did not request this, please ignore this email and your password will remain unchanged.\n'
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
res.redirect('/');
//res.redirect('/password-reset-confirmation') Make a confirmation page with information or just send a flash message
})
})], function(error){
if(error){
console.log(error);
}
})
});
The token receives the value 1 because the update() operation returns the number of affected records. In this case, there was a single record updated.
New to node.js and just cant figure out how to do the following:
I have this on my db module:
var mysql = require('mysql');
var MY_DATABASE='nodejs_mysql';
var client = mysql.createClient({
user: 'root',
password: 'root',
});
and im building this table:
client.query(
'CREATE TEMPORARY TABLE '+USER+
'(username VARCHAR(255), '+
'password VARCHAR(255), '+
'name VARCHAR(255), '+
'picture VARCHAR(255), '+
'PRIMARY KEY(username))'
);
and later on, i want to perform this:
client.query('select username, password from ' + USER + 'where username=?',[req.body.username] , 'AND password=?', [req.body.password]
function (err, results, fields) {
if (err) {
throw err;
}
//some actions performed here
});
all of those are in the same dataBase.js file.
how can i send username and password from another file named: server.js
as parameters to the query written above and get a certain value back?
is there any way to do that?
Ok, I think I get it now. You create temporary table in dataBase.js and want to perform query in this table in request handler in server.js. If that's it, you should consider following aproach:
// dataBase.js
var mysql = require('mysql');
var MY_DATABASE='nodejs_mysql';
// connect to database
var client = mysql.createClient({
user: 'root',
password: 'root',
});
// create temporary table
client.query(
'CREATE TEMPORARY TABLE '+USER+
'(username VARCHAR(255), '+
'password VARCHAR(255), '+
'name VARCHAR(255), '+
'picture VARCHAR(255), '+
'PRIMARY KEY(username))'
);
// that's what I think you need. And yes, it looks like "a good to rap" for me.
module.exports.getInfoFromTemporaryTable : function( username, password, callback) {
client.query(
'select username, password from ' + USER + 'where username=?',
[req.body.username] , 'AND password=?', [req.body.password],
callback
);
}
The only thing I can't figure out is where you get USER variable from. Pay attention to this moment. Maybe pass it to getInfoFromTemporaryTable() function.
// server.js
var db = require('./lib/dataBase');
app.get(someRoute, function(req, res) {
db.getInfoFromTemporaryTable( req.body.username, req.body.password,
function(err, results, fields) {
if (err) {
// handle errors or something
return;
}
// do what you need to do, using results you got from temp table
});
});
I'm not familiar with MySQL module you using, so above code is more like a general idea of what you need to implement. Hope it will help.
how can i send username and password from another file named: server.js
as parameters to the query written above and get a certain value back?
Use the exports object. See here for more information on NodeJS's module system.
// server.js
exports.username = function {
return "foo";
};
exports.password = function {
return "bar";
};
// database.js
require('./server.js');
var client = mysql.createClient({
user: server.username, // exports.username in server.js
password: server.password, // exports.password in server.js
});
Why are you splitting your query up?
// server.js
exports.username = "Your username.";
exports.password = "Your password.";
// dataBase.js
// ... mysql connection setup ...
var server = require("./server");
client.query('SELECT username, password FROM `' + USER + '` WHERE username=? AND password=?',
[server.username, server.password],
function (err, results, fields) {
if (err) {
throw err;
}
// ... some actions performed here ...
}
);
I'm not exactly sure what you were asking, but I think this should at least get you closer to your answer.