Faulty SQL query in JavaScript? - javascript

Before I start, I'm aware of the risks I'm taking by connecting to a database via JavaScript. The thing with this project is that it's going to be for a slightly different purpose, so I'm fine with using JavaScript.
document.getElementsByClassName("option")[0].onclick = function() {
event.preventDefault();
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "dbname"
});
con.connect(function(err) {
if (err) throw err;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var sql = 'SELECT * FROM accounts WHERE email = ' + mysql.escape(email) + ' AND password = ' + mysql.escape(password);
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
So, I had technically done this before with PHP. It's just that I'm now doing it with JavaScript. Yet, something is clearly wrong. As you can see, I want to see the result in the console. Yet, I'm left with this:
I can't say I'm an experienced programmer - the truth is, this is just some kind of practice project, I'm a student. So any kind of help would be appreciated!

You need to quote strings in SQL. You didn't put quotes around the email and password.
But it's better to use parameters rather than substituting variables into the SQL, even if you escape them.
var sql = 'SELECT * FROM accounts WHERE email = ? AND password = ?';
con.query(sql, [email, password], function (err, result) {
if (err) throw err;
console.log(result);
});

Related

How can i modify a global variable from within a callback function . in node.js

In node.js , and i wanna store the result of a mysql query in a global variable so i can export it or log it to the console whatever , but it seems that the global variable is not modified from within the callback function , so what can do ? pleaase help , tgis is my simple code
var mysql = require("mysql");
var text = "begin : ";
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "ajax",
});
con.connect(function (err) {
if (err) throw err;
var sql = "SELECT * FROM `nom`";
con.query(sql, function (err, result) {
if (err) throw err;
result.forEach((row) => {
text +=
" the first is : " +
row.first +
" and the second is : " +
row.second +
"\n";
});
});
con.end();
});
console.log(text);
Your current code is not entirely synchronous i.e. line 1, line 2 and line 3 may execute as line 1, line 3, line 2. Your code is asynchronous because you have a call to con.connect which uses callbacks (i.e. it will call the function you provided when it has attempted to conenct to your mysql db). If you would like to print the text after the connection it would not be recommended to use a global variable or more precisely have your console.log(text); at the end of your code since the console.log(text); may run before con.connect has attempted to connect to your database. The following is therefore one recommendation for this specific example:
var mysql = require("mysql");
var text = "begin : ";
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "ajax",
});
con.connect(function (err) {
if (err) throw err;
var sql = "SELECT * FROM `nom`";
con.query(sql, function (err, result) {
if (err) throw err;
result.forEach((row) => {
text +=
" the first is : " +
row.first +
" and the second is : " +
row.second +
"\n";
});
console.log(text);
//write code to export to file/remote service here
});
con.end();
});
Javascript Function Scope is another peculiar interest which I have linked to and many resources are available which describe and explore this. It is recommended that in your future code, especially since you are working with asynchronous code that you try to localize or work within your function scope and avoid using global variables that will be modified by different functions at different times which can be difficult to predict and will therefore consider your project/code "unpredictable".

ER_PARSE_ERROR node.js and mysql issue (INSERT INTO)

I want to do a simple insert with Node.js while I am using socket.io with node.js and MySQL. Don't know why, but I am geting this error
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 ''markos'' at line 1
My code:
When I try this, I get the above error.
io.on("connection", function(socket){
console.log("a user is connected " + socket.id );
socket.on("question", function (question){
let sql = "INSERT INTO nodeJs (name) VALUES ?";
con.query(sql, question, function (err) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
if I try this simple code, everything works fine:
io.on("connection", function(socket){
console.log("a user is connected " + socket.id );
socket.on("question", function (question){
let sql = "INSERT INTO nodeJs (name) VALUES ('John')";
con.query(sql, function (err) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
The question parameter always has a string.
You're missing the parentheses around the values:
let sql = "INSERT INTO nodeJs (name) VALUES (?)";
// Here ------------------------------------^-^

Node.js mysql query returns empty array

I wrote node.js script and it works not as expected.
Here is my js code, that describes mysql connection;
var mysql = require('mysql');
var createConnectionMYSQL;
var connectCount=0;
(createConnectionMYSQL = function () {
con = mysql.createPool({
connectionLimit:10,
host: "*****",
user: "*****",
password: "********",
database: "dbname"
});
console.log(++connectCount);
})();
con.query("SET SESSION wait_timeout = 120");
con.query('set names utf8');
con.on('error', function (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
createConnectionMYSQL();
} else {
throw err;
}
});
Main function returns promise that I handle.
function getRecipes(str, page) {
return new Promise(function (resolve, reject) {
//unimportant code
var sql = 'SELECT ID, Recept, MATCH (Recept) AGAINST ("+' + ingredients[0] + '*" IN BOOLEAN MODE) as REL FROM recipes WHERE (MATCH (Recept) AGAINST ("+' + ingredients[0] + '*" IN BOOLEAN MODE))>0 ORDER BY REL';
if (page != 0) sql += ' LIMIT ' + (page * 12) + ' ,12';
con.query(sql, function (err, result, fields) {
if (err) return reject(err);
// console.log(result + ' ' + sql);
resolve(result);
});
});
}
But I get strange behavior of mysql module. In getRecipes(par1,0).then(function(results){}) I get first empty array and one minute later I get normal array with results as if resolve() worked twice. But it's Lucky case. Sometimes I got more empty arrays and then expected array with results.
I think the return in 'return reject(err)' is unnecessary, but that shouldn't explain this behaviour.
Do you have the connection part in the same promise loop that handles the query? So that first you check with promise that connection is ok, and after that, you make the query? If not, then that might cause some problems.
Have you checked from the database, that how many requests are coming?

Node JS synchronous Database Calls

i am pretty new to java script and nodejs.
i am trying to write a code that checks if an email is already exists in the database, and if not send an error.
the problem is that before the database function is ending, my code going to the next line, resulting in undefined variable(emailExists)
this is my code for the sign Up:
app.post('/signUpWeb', function (req, res) {
var reqBody = req.body;
var email= reqBody.email;
var password= reqBody.password;
var fullName= reqBody.fullName;
var webDbInsertion = {email: email, password: password, fullName: fullName};
var emailExists= DButils.checkIfPKexists(connection, "webusersMail", "email", webDbInsertion.email);
if(emailExists == false){
DButils.insertInfoToDB(connection, "webusersMail" ,webDbInsertion);
console.log("successfull signup");
res.send("successfull signup");
}else{
console.log("signup failed, email: " + email + " allready exits");
res.send("signup failed");
}
res.end();
});
and this is for my database call
exports.checkIfPKexists= function(dbConnection, tableName, PK, newPK){
var query = dbConnection.query('select count(*) as mailPkCount from ' +tableName+ ' where ' +PK+ ' = ?', newPK, function (err, row, result) {
if (err) {
console.error(err);
return;
}
var count= row[0].mailPkCount;
var bool = (count > 0);
return bool;
});
};
Well you see, node.JS is designed to be async, while what you're asking isn't impossible, it would shut down the main thread that runs the event loop for that instance of your server.
What I suggest doing is adding a callback function to your "checkIfPKexists" function, and return with the result as a parameter, much like you do in the DBConnection.query. You would then move all the code that isn't getting initialized into your callback.
Edit: Heres a quick code example, polish it up to your liking http://pastebin.com/bEHp4bi2

NodeJS - how can get mysql result with executed query?

I am new in NodeJS with mysql (npm install mysql).
When I try to execute query like
connection.query("select ?? from users where id = ?",[["id","fname","lname"],req.body.userid],function (err, rows) {
**here I want query which above executed**
});
I want query in callback function which executed.
How can I get it??.
var c = connection.query("select ?? from users where id = ?",[["id","fname","lname"],req.body.userid],function (err, rows) {
console.log(c.sql)
});
connection.query("select ?? from users where id = ?",[["id","fname","lname"],req.body.userid],function (err, rows) {
res.send(rows);
});
also in preference swith the string query to :
"select id,fname,lname from users where id = '"+req.body.userid+"'"

Categories

Resources