Nodejs with Mysql Database - node.js

I'm using nodejs with MySQL for the first time , I'm struggling to properly preparing statements ,I have no problems when writing and executing some insertion statements but when i tried to write the selection statements i can't know what is the correct syntax .I can't find tutorial for the beginner
This is the selection code
io.sockets.on('connection', function(client) {
client.on('check_id', function(login_feilds) {
console.log(login_feilds);
var login_feilds_as_json = login_feilds ,
Email = login_feilds_as_json.email ,
password = login_feilds_as_json.password ;
var sql = "SELECT * FROM ?? WHERE ?? = ? AND ?? = ?";
var inserts = ['users', 'email', Email,'password',password];
sql = mysql.format(sql, inserts);
console.log(sql);
connection.query( sql , function(err, rows){
if(error){
console.log(error.message);
}else{
console.log('found it'); };
});
});
});
when I run the above code I got this
{ email: 'user#windowslive.com', password: 'user' }
SELECT * FROM `users` WHERE `email` = 'user#windowslive.com' AND `password` =
'user'
C:\Users\jiil\Desktop\our-project\node_modules\mysql\lib\protocol\Parser.js:82
throw err;
^
ReferenceError: error is not defined
could you help me to figure out what i have to do or give me any good resources' links .

The problem is that you wrongly use variable name in your callback function. You need to change error to err.
connection.query(sql, function(err, rows){
if (err) {
console.log(err.message);
} else {
console.log('found it');
}
});
Hope it will be useful for you.

Related

"query values must be an array"...?

As the title reads, I am receiving a "query values must be an array" error when writing Node.js code to attempt to query a local (postgres) database. Here is the code I am using:
var pg = require('pg');
var conString = "postgres://user:pass#localhost:5432/mydatabase";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT $1::text AS name', 'howdy', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].name);
client.end();
});
});
I believe this refers to the need to have the query string use array values rather than a direct string...however I am unsure how to structure the code. Any advice would be greatly appreciated. I thank you in advance. Regards.
The error is right. The second parameter to query should be an array. This is a paramterized query
client.query('SELECT $1::text AS name', ['howdy'] ...

query issue in postgres

I am using the following code snippet in a Node.js application to attempt to query a (local) postgres database:
var conString = "postgres://user:password#localhost:5432/mydatabase";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query("SELECT * FROM users WHERE name = $1 AND cred = $2", [String(req.body.usr), String(req.body.pword)], function(err, result) {
if(err) {
return console.error('error running query', err);
}
if (typeof result.rows[0] === "undefined") {
console.log("No user/password determined in DB for login attempt");
} else {
} //user/password is 'undefined' (NOT found in database)...OR NOT...
client.end();
});
});
I am receiving an error when the query runs...I believe the problem may possibly be the number of parameters in my query call...? If that is the case (or it is some other syntax problem) could anybody be so kind to inform how I should change the code to perform the query correctly...?
I simply need to take 2 (user-supplied) results from a form (req.body.usr and req.body.pword) and compare them to the database table 'users' to determine if the credentials are correct. I already believe the database connection works properly. Any advice greatly appreciated. I thank you in advance.
Change:
client.query("SELECT * FROM users WHERE name = $1 AND cred = $2", [String(req.body.usr), String(req.body.pword)], function(err, result) {...
to:
const query = {
text: "SELECT * FROM users WHERE name = $1 AND cred = $2",
values: [String(req.body.usr), String(req.body.pword)]
};
client.query(query, function(err, result) {
Read more: https://node-postgres.com/features/queries

Im getting SQLITE_Error: no such column, but it exists why?

Im trying to get the rowid from the database where there is someone with the same username from the guy who just wrote a message. The code works when I change
WHERE creator` =${member.username} to WHERE matchid =` ${matchid}.
It gets me the rowid from that match. But I want to get the rowids from where the user is the creator. (I checked my db and on the creator column there is the name of the username Boanak). The error that im getting is this: { Error: SQLITE_ERROR: no such column: Boanak errno: 1, code: 'SQLITE_ERROR' }.
My code:
var getMatchid = function(client, message, callback) {
//let matchid = parseInt(args.join(' '));
let member= message.member.user;
var db = new sqlite3.Database('Matches');
db.serialize(function() {
db.all(`SELECT rowid
FROM Match
WHERE creator =`+${member.username}, function(err, allRows){
if(err) {
//console.log(err);
callback(err, null);
}
else {
callback(null, allRows);
}
db.close();
});
});
}
getMatchid(client, message, function(err, data){
if (err) {
console.log(err);
}
else if (data && data.length) {
message.channel.send(`Match ${data[0].rowid} found`);
}
else {
message.channel.send("That match ID doesnt exist.");
}
});
You need to encapsulate your variable in a string. You're also using template literals, so you can put the expression directly inside.
`SELECT rowid
FROM Match
WHERE creator = "${member.username}"`

Query MySQL using Prompt user input (Node.js)

I am trying to allow a user to input criteria (i.e. Client) for my application to query a mySQL database and return all matching results. My connection is established and I am able to hardcode my query (connection.query("select * from ACHLookerUpper where Client = ?", ["ex."]) and return expected results. I can also simply run the Prompt command and intake and console.log my input.
However, when I try to combine the two -- intake user input via Prompt and query -- I cannot successfully pass input into my query. I am somewhat new to node so I'm sure there's an issue in my nesting, however the error is not very helpful other than telling me "Cannot enqeue Query after invoking Quit".
I'm sure I need to store results.Client as a var or param then call it in my query but can't figure out how.
var mysql = require("mysql");
var prompt = require('prompt');
var connection = mysql.createConnection({
host: "<host>",
user: "<user>",
password: "<pw>",
database: "<db>",
port: "<port>"
});
connection.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
});
prompt.start();
prompt.get(['Client'], function (err, result) {
if (err) { console.log("Error");
return;
};
connection.query("select * from ACHLookerUpper where Client = ?", [result.Client], exports.MyHandler = function(err, rows){
if (err) {
console.log(err);
return;
}
rows.forEach(function(result) {
console.log(result.ID, result.Name, result.Client, result.ACH);
})
})
});
connection.end(function(err) {
});
prompt.get() is asynchronous, so connection.end() is getting called first and then later on you try to execute the query when input has been received for the prompt, but the connection has already ended at that point.

Unable to post via express using bodyparser

I have a web app containing four routes out of which two are executing insert query in Postgresql and two are executing select query. The post in insert is working fine but post in select query is not working. Is this problem of the query or post i'm unable to understand. Printing the post var gives undefined. Please help.
ws.post('/prab',function(req,res){
var vill = req.body.addr;
console.log(vill);
if(!(vill = null) )
{
pg.connect(conString,function(err,client,done){
if(err){
return console.error('Could not connect to postgres' , err);
}
var results = [];
var query = client.query("SELECT * FROM \"Area_info\" WHERE \"FOLDER_NAME = $1",[vill],function(err,result){
console.log(vill);
console.log(query);
query.on('row', function(row) {
results.push(row);
});
query.on('end', function() {
done();
return res.json(results);
});
if(err) {
return console.error('error running query', err);
}
else{
if(results.length == 0)
{
res.render('abs');
}
else{
res.render('re');
}
}
})
})
}
});
I solved my problem. It was silly on my part as i picked bootstrap template , i forgot to change the type of button from button to input. Thanks everybody to help me and waste your precious time on my silly mistake. I would be careful from next time.
This might be your problem:
if(!(vill = null) )
You're doing an assignment to vill and not the equality operator (== or ===). The assignment operator according to the Node REPL returns whatever is on the right hand side which in this case is null. Therefore, the statement (!(vill=null))above will always evaluate to true.

Resources