How to get only name of user from database in node.js - mysql

I am retrieving user name of the person who is logged in from database. BUt i am getting results like
[RowDataPacket { First_Name= 'Rani'} ] But i only need to get that "Rani'. How to do that in node.js?
I only want to get username except those extra parameter(First_Name) e.g "Rani" in above case.
This is part of code where i am getting value.
I have tried var myJSON = JSON. stringify(obj) but it shows [ { First_Name= 'Rani'} ].
app.post('/auth', function(request, response) {
var number = request.body.number;
var password = request.body.pwd;
var qu = `SELECT
First_Name
FROM fyp_helpers
WHERE Mobile_number = ?
UNION
SELECT
Employer_Fname
FROM fyp_employers
WHERE Employer_Contact = ?`;
connection.query(qu, [number, number], function (error, results, fields){
if (error) throw error;
else
{
console.log(results);
..........

The column names from the query become properties of the objects that represent the rows of results. So use
console.log(results[0].First_Name);

Related

How to update one or more fields ignoring empty fields in NODE MySQL

I use MySQL and NodeJS and my objective is to update a profile row. But no matter what field the user will chose to update, the backend should ignore the empty field and update the chosen field.
exports.update = (req, res, next) => {
const url = req.protocol + '://' + req.get('host');
let NewURL = req.file.path.split('\\')[1]
const image = url + '/images/' + NewURL; // req.file.path
let postID = req.params.id;
let { title, subtitle, content } = req.body;
//? tilte : oldvalue.title}
const sql2 = `Select * from posts where post_ID = ${postID}`;
db.query(sql2, (error, result) =>{
if (error) throw error;
else {
console.log(result);
const sql = `UPDATE posts
SET
post_title = '${title ? title : result.post_title }' ,
post_subtitle = '${subtitle ? subtitle : result.subtitle }' ,
post_content = '${content ? content : result.content}' ,
imagesLink = '${image ? image : result.image }'
WHERE post_ID = '${postID}'
`;
db.query(sql, (error, result) =>{
if (error) throw error;
else {
res.send(result);
}
});
}
})
}
In this function I tried to implement two sql queries and using the ternary operator, replace the old value from the db with the new value.
Still, I get the undefined fields in the DB and the backend request that the image is required to be updated...
Can somebody help? Thanks.

Struggling to print multiple MySQL rows to a web page using Node.js

Trying to build a simple web app using Node.js. One of the pages requires multiple rows from one of my SQL table columns to be printed out like so:
Here is the most recently added string from column X
Here is the second most recently added string
Here is the third
Here is the fourth
Here is the fifth
I've got the hang of printing the first row using something like this:
var q = 'SELECT mycolumn AS string FROM users';
connection.query(q, function (error, results) {
if (error) throw error;
var string = results[0].string;
res.render('thanks', {string: string});
});
});
However, I can't figure out how to print the results from rows 1-5. Closest I've got from Google is:
connection.query('SELECT mycolumn AS string FROM users LIMIT 5', function (error, results) {
if (error) throw error;
var string = JSON.stringify(results);
res.render('thanks', {string: string});
});
});
but this gives me [{"mycolumn":"The content I'm trying to isolate"},{.....etc ] as the output and I can't figure out a way to clean that up.
I believe that by specifying results[0] you are only getting the record with the index of 0 - which should be the first one.
Here is a sample of select query in one of my apps:
app.get('/categories', async(req, res) => {
try {
const allCategories = await pool.query("SELECT id, title FROM categories WHERE visible=true ORDER BY id desc");
res.json(allCategories.rows);
} catch (error) {
console.error(error.message);
}
});
You can see I don't have the [0] on my rows result.
Solved it:
connection.query(q, function (error, results) {
if (error) throw error;
var string1 = results[0].string;
var string2 = results[1].string;
var string3 = results[2].string;
res.render('thanks', {string1: string1, string2: string2, string3: string3});
});
});```

Undefined push to array - Basic Application using ExpressJs and MySQL

First of all, I have to tell you I'm pretty noob in this "universe". I'm using: ExpressJs, MySql, Body-Parser, Express-session, Ejs template for creating an Basic Contacts Application in Node.
My database is composed from 3 tables:
user (user_id, first, second name, username, password)
contacts (ct_id, first, second name, phone numb.)
user_contacts (user_id, ct_id) --> foreign keys for user and contacts
I want to listing on /myProfile page all details about user and his contacts.
I don't know how to handle the select queries.
So, after some documentation I did this:
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
console.log(result);
var queryArray = "";
for(var i = 0; i < result.length; i++){
queryArray += `SELECT * FROM contacts WHERE ct_id= ${result[i].ct_id}; `;
}
console.log(queryArray);
conn.query(queryArray, function (err, result) {
if(err) throw err;
console.log(result);
res.render('myProfile/contacts', {
title: `${req.session.user_nickname}'s Contacts`,
data: result
});
});
});
But I have an error
ER_PARSE_ERROR: You have an error in your SQL syntax;
..when queryArray.length > 1
I searched and it's something about Multiple statement queries but I dont know how to solve it.
Edit 2:
I modify my code..
conn.query('SELECT * FROM user_contacts WHERE user_id= ?', req.session.user_id, function (err, result) {
if(err) throw err;
var datas = [];
for(var i = 0; i < result.length; i++){
getContacts = function(query){
conn.query(query, function (err, result) {
console.log('Creating data');
data = {
user: req.session.user_nickname,
contact:{
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
}
}
return data;
});
}
console.log('Send data to array');
datas.push(getContacts(`SELECT * FROM contacts WHERE ct_id = ${result[i].ct_id}`));
}
console.log(datas); // [ undefined, undefined ]
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: datas
})
});
But now my array contain undefined objects?? Any solution?
Maybe is something about scope?
My result:
Send data to array
Send data to array
[ undefined, undefined ]
Creating data
Creating data
I push the object to array before creating it. How is it possible?
1797,
I noticed you have several small queries grabbing the contact info for a given user. You could simplify your code by combining your queries into a single one. Often times 1 big query is more efficient (plus it's easier to maintain). I'm using a join. More info here.
const contacts = [];
const query = "
SELECT c.*
FROM user_contact uc
JOIN contact c ON uc.contact_id = c.contact_id
WHERE uc.user_id = ?
GROUP BY c.contact_id
";
conn.query(query, req.session.user_id, (err, results) => {
if (err) throw new Error(err);
// it seems that this could just be 'contacts = results' since they
// have the same structure
contacts = results.map(result => {
return {
ct_firstName: result[0].ct_firstName,
ct_SecondName: result[0].ct_SecondName,
ct_PhoneNumber: result[0].ct_PhoneNumber
};
});
res.render('myProfile/contacts',{
title: `${req.session.user_nickname}'s profile`,
data: contacts
});
});

Nodejs-Mysql Query table name as a variable

How can i pass table name as variable. Basically i want to make e function in which i will take table name as a parameter and object insert record in mysql database in using nodejs
My function will be like
exports.insertIntoDb = function(tableName,insertObj) {
connection.query('INSERT INTO administrator SET ?',insertObj, function(error, result, fields) {
if(error){
res.json({
status:false,
message:'There is some problem with query'
})
}
else{
res.json({
status : true,
data : result,
message: 'user registered successfully'
})
}
});
}
But i am wondering that how to pass table name in this query which is parameter taken from function. I am asking about syntax? I am using nodejs-mysql
Try this:
exports.insertIntoDb = function(tableName,insertObj) {
connection.query('INSERT INTO ?? SET ?', [ tableName, insertObj ], ...)
};
Documented here: https://github.com/mysqljs/mysql#preparing-queries
Inside app.js:
app.put('/updateCell', async function(req, res) {
console.log("REST: PUT /updateCell");
let orderInfo = req.body;
let cellValue = orderInfo.cell;
let CustomerName = orderInfo.CustomerName;
let ColumnName = orderInfo.columnName;
connection.query("UPDATE vehicles SET ?? = ? WHERE order_CustomerName = ?", [columnName, cellValue, customerName],
function(err, result) {
if (err) throw err;
});
res.send();
});
example:
//cellValue = "Fluffiest hat of them all";
//customerName = "Jenny Hopkins";
//columnName = "description";
So the SQL query would be the same as:
UPDATE order SET description = "fluffiest hat of them all" WHERE order_CustomerName = "Jenny Hopkins";

Do you need brackets around Mysql parameters to prevent sql injection?

I am using nodejs and the mysql npm package and I'm trying to select from a table where other_text =
Here is what it looks like:
var query = connection.query(`SELECT id FROM ${tableName} WHERE other_text = ?`,
attributeName.other_text, function (err, rows) {
...
I have read that using ? will automatically escape the user entered string. In most of the examples that I see that do this, they have brackets around the 2nd parameter in the query function, like below:
var query = connection.query(`SELECT id FROM ${tableName} WHERE other_text = ?`,
[attributeName.other_text], function (err, rows) {
...
Are the brackets necessary in order to escape the string that's passed in? It works when I try it, but I don't even know how to test a SQL injection so I don't really know if the brackets are necessary or even correct.
Thank you.
The brackets represent an array. You can use an array in case you have more values you want to use with your query.
For example, let's say that you want to select multiple columns from the table, and you want to pass them to the statement, you would use something like this:
connection.query(`SELECT ?? FROM ${tableName}`,
[col1, col2, col3], function (err, rows) {
It also does work in combination with strings, numbers or even objects. Let's say that you want to update the user with id 1 from Users table table. You would do something like this:
const tableName = 'users';
const whereCondition = {id: 1};
const whaToUpdate = {name: 'newName'}
const mysql = require('mysql');
const statement = mysql.format('update ?? set ? where ?', [tableName, whaToUpdate , whereCondition]);
I also recommend using .format for better code reading.
Finally you would have something like this:
connection.query(statement, (error, result, fields) => { });
The bracket uses for passing multiple values. You can use escape function or question mark (?) placeholder to prevent SQL injections. Lets have a look in details:
We are using mysql node module to provide all example below (Example 1 to Example 5). The below code is necessary to follow those example.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
MySQL con.query has overloaded function.
Example 1: it takes sql string and callback function
var sql = 'SELECT * FROM customers;
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
Example 2: it takes sql string, parameter and callback function
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
if (err) throw err;
console.log(result);
});
In Example 2, the second parameter uses [ ] so that you can pass
array to provide multiple values as parameter. Example 3 shows how to pass multiple values in second parameter.
Example 3: Here two values are passed name and address into [ ]
var name = 'Amy';
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE name = ? OR address = ?';
con.query(sql, [name, adr], function (err, result) {
if (err) throw err;
console.log(result);
});
Preventing SQL injections
To prevent SQL injections, you should use escape function the values when query values are variables provided by the user.
Example 4: Here we used escape function to avoid SQL injections
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ' + mysql.escape(adr);
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
Example 5: Escape query values by using the placeholder ? method
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
if (err) throw err;
console.log(result);
});
More details