Can't access object properties - mysql

I am using NodeJS and node-mysql, I've created a DB layer to allow easy integration with other DBs (example MongoDB) for later use. At this point in time, the syntax is essentially the same as MySQL.
I am placing a call to the query object of MySQL, and it's returning the results to my callback function, which I can send to the console with console.log, and it shows the following:
[ { username: 'test', total: 1 } ]
Yet, when I try to access the total, it says undefined. Here's my code:
db.query("SELECT username, COUNT(user_id) AS total FROM users WHERE username = '" + message.username + "'", function(err, info) {
console.log(info);
self.sendRequest(client, '{ "command" : "CALLBACK", "result" : ' + info.total + ' }');
});
when using console.log(info), it returns valid JSON syntax, however I cannot access the total via info.total, as it returns undefined....
Any ideas on why I'm having this issue? If you need to see more code I will be happy to provide it..

Figured it out;
info[0].total returns what I need (d'oh)...

Related

Pass variables to DATABASE preventing mysql injection node and mysql

So, I started to develop in nodejs and mysql. I read in some forums that the correct way to do the insertion in mysql would be using variables to prevent mysql injection, however I tried in several ways to insert them and I couldn't. I was only able to do them manually as follows:
db.query('UPDATE spreadsheetUsers SET weight="1" WHERE weekDay="1" AND idStudent="1" ', (error,results) =>
How could I do to insert them using variables?
The way I was trying was like this:
db.query('UPDATE spreadsheetUsers SET weight=? WHERE weekDay=? AND idStudent=? '
,{weight:value[0], weekDay:daySelected, idStudent:idStudent }, (error,results) =>
I guess im missing something, could someone help?
https://github.com/mysqljs/mysql#escaping-query-values
{weight:value[0], weekDay:daySelected, idStudent:idStudent }, (error,results) =>
the parameterized query should be array not object
db.query('UPDATE spreadsheetUsers SET weight=? WHERE weekDay=? AND idStudent=?'
,[value[0], daySelected, idStudent], (error,results) =>
You can use this style also
db.query({
sql: 'UPDATE spreadsheetUsers SET weight=? WHERE weekDay=? AND idStudent=?',
values: [value[0], daySelected, idStudent']
}, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});

How to fetch string data stored as array in mysql

I have stored some unique codes in MySQL as array in respective to user email, now i want to verify the user with email and unique code submit by user. I want to create a query where i can match email and unique id stored in database, to proceed the user.
Database Entry:
["BZFeWwnmr8Rm6tuu","daFJWZCEtp2WzxtD","VV80UQQZ1ym77h0m"]
I have tried FIND_IN_SET
This is the code for API, I have stringify the user entered data, where it returns the value if there is single unique value stored, But if i fetch array of unique code e.g, ["BZFeWwnmr8Rm6tuu","daFJWZCEtp2WzxtD","VV80UQQZ1ym77h0m"]
the MySQL query not working.
exports.vr_client_detail = function (req, res) {
const JSON_DATA = 'application/json';
if(req.headers['content-type'] === JSON_DATA){
if (req.body) {
var unique_string = JSON.stringify(req.body.unique_string);
var email = req.body.management_email;
db.sequelize.query('SELECT * FROM im_vr_client_activation '+
'WHERE FIND_IN_SET(unique_string, '+"'"+unique_string+"') AND "+
' management_email= ' + "'" + email + "'").then(function(app){
var arr = app[0];
return res.json({response_status:'success', response_code:185, data:arr, response:'Successfully fetch data.'})
});
}else{
return res.json({response_status:'error',response_code:10001,response:'Post data is empty.'});
}
}else{
return res.json({response_status:'error',response_code:10000,response:'Post data is not a json type.'});
}
}
The data returns nothing
{
"response_status": "success",
"response_code": 185,
"data": [],
"response": "Successfully fetch data."
}
It would be best if you normalized your schema, using a many-to-one table to hold all the unique strings instead of putting them into a single column.
But if you can't do that, you need to remove the [ and ] characters so you can use FIND_IN_SET().
You should also use a parametrized query to prevent SQL injection. See How to create prepared statements in Sequelize?
db.sequelize.query('SELECT * FROM im_vr_client_activation '+
'WHERE FIND_IN_SET(:unique_string, SUBSTR(unique_string, 2, LENGTH(unique_string)-2)) ' +
'AND management_email = :email', {
replacements: { unique_string: unique_string, email: email }
}).then(...)
If you're using MySQL 5.7 or higher you can change the datatype of the column to JSON and use JSON_CONTAINS(). And in 8.0 you can use the MEMBER OF operator.

Why my database displays undefined even I inserted data in POSTMAN?

Below is my code for inserting data in MYSQL in ExpressJS.
router.post('/user', function (req, res) {
let sql = "INSERT INTO Member (id, Memb_ID, First_Name, Middle_Name, Last_Name, Address, url) VALUES (null, '" + req.body.Memb_ID + "', '" + req.body.First_Name + "', '" + req.body.Middle_Name + "', '" + req.body.Last_Name + "', '" + req.body.Address + "', '" + req.body.url + "')";
myDB.query(sql, function (err, results) {
if (err) throw err;
res.send({
Success: "Data inserted."
})
});
});
It inserts data in my database but my database looks like this
I don't know why it outputs like that. Here's my JSON
EDIT :
Here is my MYSQL Table
Can you make sure that the following is done?
The content-type header in the request has to be application/json
Use body-parser (or similar libraries) to parse JSON payloads -> You can print the req.body to validate this.
If you can confirm that the values are accessible, I would suggest escaping query values as mentioned in https://github.com/mysqljs/mysql#escaping-query-values (or in any mysql library that you use) - especially since it is a DML query.
(Also I assume that the fieldnames used in the query match with the ones in the database and are of the right datatype.)
In your image of postman call, it's clearly showing your content type is text.
Change Content-type to application/json in your postman call headers
Or you can select from body tab
As your body content was text as shown in your image, it was sending a plain text that leading to undefined in DB. But the server was expecting json.
Hope that helps.
See wether you have added #RequestBody annotation in your respective method signature in Controller...
check this 1's bcz i had same issue i resolved after adding this..
it may help you and others... also...

Completed 500 Internal Server Error in Ruby on Rails

I'm trying to do a search but did not get any result. This is wrong:
def BuscarRoles(usuario)
#sql="SELECT * FROM rols WHERE id_rol IN (SELECT id_rol FROM rol_usuarios WHERE id_usuario = "+usuario.to_s+")"
#roles = ActiveRecord::Base.connection.execute(#sql)
#tira='['
if #roles.count>0
#aroles.each do |rol|
#tira = #tira+" { id_rol: '" + rol.id_rol.to_s + "', descripcion: '" + rol.descripcion.to_s
j=j+1
if j<#roles.count
#tira = #tira+ " }, "
else
#tira = #tira+" } ] "
end
end
else
#tira= #tira+"{ { text: 'No hay datos', id: '0', href: '', leaf: true } } ]"
end
return #tira
end
By just looking at the code, with no trace given, I can only see one thing that might cause the error.
ActiveRecord::Base.connection.execute
#the result of the above code is Mysql2::Result of course depending on what database you're using.
Hence you can't use .(dot) operator on the result as you would do on a model object.
So you could make the following changes in the code
#aroles.each do |rol|
#puts rol.id_role => this will throw error
puts rol[0] # this should work assuming id_role is the first column
end
That should help. As you mentioned in the comment that your getting error in #aroles.each do |rol| then you must check if the sql statement is returning you any results at all ?
BTW, even if the query doesn't return any results, it would simply return an empty array and iterating an empty array would simple give nothing but not throw any error.
So to conclude
Check if any records are returned at all
Use index instead of the column name as they are active_record objects
Hope that helps.

js $.ajax calling perl, need to display perl which returns fetchall_arrayref

My $.ajax is calling a Perl file which returns data from MySQL in a fetchall_arrayref.
How can i get the data back into ajax and put into the <select> dropdown options in the jQuery? it is returning something from perl, but the <select> dropdown displays the whole ajaxFunctions.pl file, char by char - each char is a selection. it needs to call the Perl file, do the mySQL SELECT there, and return the SELECT query result to the $.ajax "data" section so that I can show it in the GUI. I tested the MySQL query which works fine [returns 3 items, group names].
Here is the perl code:
if ($q->param('ajaxAction') eq "getGroups") {
my $return;
eval {
my $query = qq(SELECT DISTINCT group FROM dbtable ORDER BY group);
my $dbh = dbConnect();
my $sth = $dbh->prepare($query);
$sth->execute();
$return = $sth->fetchall_arrayref();
};
if ($#) {
$return = {'STATUS' => 'FAIL',
'ERROR' => 'Error getting the group names. ' . $#};
}
print $q->header('application/json');
print to_json($return);
exit(0);
}
and here is the Javascript code:
function getGroups() {
$.ajax({
type: 'POST',
url: '/Project/metrics/cgi-bin/ajaxFunctions.pl',
data: ({ ajaxAction: 'getGroups'}),
success: function(data) {
for(var i =0; i < data.length; i++) {
$("#groupReportSelect").append('<option value="' + data[i] + '"> ' + data[i] + '</option>');
}
$('#groupReportSelect').multiselect();
$("#groupReportSelect").multiselect("checkAll");
getData();
},
error: function(request, status, err) {
console.log('Error fetching groups. ' + err);
}
});
}
Again, the output is each option in the select is an individual character of the whole perl file, starting with "#", "!", "/", of #!/usr/bin/perl, etc., etc.
Please let me know if I have left anything out. I have read several other posts, and am trying to give you all the appropriate data to answer my question.
Your AJAX request appears to be fetching the entire perl file listed in the object's url: property (i.e '/Project/metrics/cgi-bin/ajaxFunctions.pl',) rather than the output from a REQUEST to that URI.
This is most likely due to your CGI and HTTP server environment being improperly set up. Your web server needs to have a CGI Handler set up to serve .pl files correctly as applications and not as files.
You haven't configured your server to run the Perl program so it is returning it as plain text.
You'll need to consult the documentation for your webserver for how you execute the program.
You appear to be writing CGI (don't do that, write PSGI and then use a CGI handler to deploy if it you really need CGI) so use that as your search term in the manual.
Here is a detailed tutorial on how to do it with Apache.