Javascript variables not working with MYSQL - javascript

I am trying to pull data from a table in MYSQL and save it to another table. Here is my code:
The two tables have the exact same columns. NOTE: The row does get saved but every value is apparently zero. Whenever I save this, MYSQL makes a new row with an index but all values are zero.
client.query('SELECT * FROM archive ORDER BY stamp LIMIT 1', function(err, result){
var nor = result[0].Northatt;
var eas = result[0].Eastatt;
var sou = result[0].Southatt;
var wes = result[0]. Westatt;
var time = result[0].stamp;
client.query("INSERT INTO quartly (Northatt, Eastatt, Southatt, Westatt, stamp) VALUES ('+nor+','+eas+','+sou+','+wes+','+time+')", function()err{
});
});
All of the variables are holding their respective 'int'...pretty sure I'm using the right syntax to save variables too.
Any help would be appreciated!

you have missed double quotes like that
VALUES ('" +nor+"','"+eas+"','"+sou+"','"+wes+"','"+time+"')

Escape parameters client side:
client.query('SELECT * FROM archive ORDER BY stamp LIMIT 1', function(err, result){
var nor = result[0].Northatt;
var eas = result[0].Eastatt;
var sou = result[0].Southatt;
var wes = result[0].Westatt;
var time = result[0].stamp;
client.query("INSERT INTO quartly (Northatt, Eastatt, Southatt, Westatt, stamp) VALUES (?,?,?,?,?)", [nor, eas, sou, wes, time], function()err{
});
});
Or use prepared statements with node-mysql2 (that way parameters are sent independently and not as part of sql query string)
client.query('SELECT * FROM archive ORDER BY stamp LIMIT 1', function(err, result){
var nor = result[0].Northatt;
var eas = result[0].Eastatt;
var sou = result[0].Southatt;
var wes = result[0].Westatt;
var time = result[0].stamp;
client.execute("INSERT INTO quartly (Northatt, Eastatt, Southatt, Westatt, stamp) VALUES (?,?,?,?,?)", [nor, eas, sou, wes, time], function()err{
});
});
Also you can do this in one query - see 'SQL Insert into … values ( SELECT … FROM … )' SO question

Related

How to get sqlite database Values in javascript

i need how to get values from sqlite Database for particular columns records in Javascript, i successfully inserted values in DB but do no how to fetch the values from db
Here my sample code how i inserted :
var newPath1 = __dirname + path.sep+'schedule.sqlite'
var bfr = fs.readFileSync(newPath1)
var db = new sql.Database(bfr)
db.run("INSERT into
profile_id(SNo,visit_id,date,time,profile_url,First_Name,Last_Name) VALUES
(?,?,?,?,?,?,?)",
[result,result1,date1,time1,sampleUrl,first_Name,last_Name])
var data = db.export();
var buffer = new Buffer(data);
fs.writeFileSync(newPath1, buffer);
i need a solution from this DB i need to fetch all values from First_Name
Try like this,
var stmt = db.prepare("INSERT into
profile_id(SNo,visit_id,date,time,profile_url,First_Name,Last_Name) VALUES
(?,?,?,?,?,?,?)");
stmt.run(result,result1,date1,time1,sampleUrl,first_Name,last_Name);
stmt.finalize();
db.each("SELECT First_Name FROM profile_id", function(err, row) {
console.log("First Name : "+row.First_Name);
});
finally i found the solution
var fName = db.exec("SELECT First_Name FROM profile_id")
this code works

Firebase Sorting Data Retrieval

This is the code that I have: I am trying to get data stored in the Firebase Database sorted by wage. The order of the database goes: "Posts -> PostID(.push when saving) -> Wage." I have the data retrieval working just not in order.
var PostsRef = firebase.database().ref().child("Posts");
PostsRef.on('child_added', function(data) {
var title = data.val().title;
var description = data.val().description;
var completionDate = data.val().completionDate;
var complexity = data.val().complexity;
var wage = data.val().wage;
var uid = data.val().userID;
});
You're storing the wages as string, which means that they will be sorted in lexicographical order:
1
13
2
20
3
If you want to get the results in numerical order, you should store the wages as numbers, so without the quotes.
If you store them from your code, this might require that you convert it with parseInt(wagesAsString).
After you store the wages as numbers, you can get them in order with:
var PostsRef = firebase.database().ref().child("Posts");
var query = PostsRef.orderByChild("wage");
query.on('child_added', function(data) {

Not able to get objectId in query.containedIn query with parse?

I am using parse.com as my back end.
I am using containedIn query to retrieve multiple user rows from parse "User" table.
My problem is that I am not able to get user's object Id in the success block
following is my code:
r_userIdList= ['PzpdRdKTVZ','PoJdRdKTVU','fvdRdKTVX'];
var query = new Parse.Query("_User");
query.containedIn("objectId", r_userIdList); // returns multiple rows
query.find({
success: function(r_uobject) {
var userObjId ,fName,lName,full_Name="Unknown User";
for(var i =0; i<r_uobject.length;i++){
var r_obj = r_uobject[i];
uID = r_obj.get('objectId');//not working
var u = uID.id;//not working
fName = r_obj.get('firstName');
lName = r_obj.get('lastName');
full_Name = firstName+' '+lastName;
r_userIdList[u].fullName = full_Name; //not working
}
}
});
Once I enter in the success block, I am unable to identify that which user's data has been retrieved.
Actually I need user's ObjectId because I have array called r_userIdList in which I need to store the firstName and LastName of user as Object.
IDs can usually be accessed with .id - in your case r_obj.id. Your uID.id won't work as uID is itself going to be undefined.
You also need to check that you are getting any results back at all: does r_userIdList have a length?

How can I include another parameter in my node.js web service?

Sorry if it's a tedious question, I'm just at the very beginning of understanding how JS/node.js works with post/get messages.
I'm writing a web service to query data from mongodb database based on the latitude/longitude and distance of the user. I wrote in my frontend code a following function:
// Take query parameters and incorporate into a JSON queryBody
$scope.queryUsersFromLast24Hours = function(){
// Assemble Query Body
queryBody = {
longitude: parseFloat($scope.formData.longitude),
latitude: parseFloat($scope.formData.latitude),
distance: parseFloat($scope.formData.distance)
};
// Post the queryBody to the /query POST route to retrieve the filtered results
$http.post('/queryUsersFromLast24Hours', queryBody)
// Store the filtered results in queryResults
.success(function(queryResults){
console.log(JSON.stringify(queryBody));
// Pass the filtered results to the Google Map Service and refresh the map
gservice.refresh(queryBody.latitude, queryBody.longitude, queryResults);
// Count the number of records retrieved for the panel-footer
$scope.queryCount = queryResults.length;
})
.error(function(queryResults){
console.log('Error ' + queryResults);
})
};
and it calls the method /queryUsersFromLast24Hours from my backed code, which looks as follows:
// Retrieves JSON records for all users who meet a certain set of query conditions
app.post('/queryUsersFromLast24Hours/', function(req, res){
// Grab all of the query parameters from the body.
var lat = req.body.latitude;
var long = req.body.longitude;
var distance = req.body.distance;
var dateNow = new Date(); //right now
// Opens a generic Mongoose Query. Depending on the post body we will...
var query = User.find({});
// ...include filter by Max Distance (converting miles to meters)
if(distance){
// Using MongoDB's geospatial querying features. (Note how coordinates are set [long, lat]
query = query.where('location').near({ center: {type: 'Point', coordinates: [long, lat]},
// Converting meters to miles. Specifying spherical geometry (for globe)
maxDistance: distance * 1609.34, spherical: true});
}
console.log(dateNow);
dateNow.setHours(dateNow.getHours()-24); //24 hours from now
console.log(dateNow);
query = query.where('created_at').gte(dateNow); //gte - greater then equal
// Execute Query and Return the Query Results
query.exec(function(err, users){
if(err)
res.send(err);
// If no errors, respond with a JSON of all users that meet the criteria
res.json(users);
});
});
But now, if I want to make it more universal and return the data not from the last 24 hours, but from the last xx hours given by the user, how should I modify it?
I want to create a webservice that will get not only lat/long/distance data, but also a number of hours as a POST message and returns the json with correct data. So how should I modify my frontend/backend code to include this change?
Also, right now I call it from the gui as follows:
<button type="button" class="btn btn-danger" ng-click="queryUsersFromLast24Hours()">Show data from last hour</button>
So how can I modify it also to pass a specific number of hours that will be included in the backend query search?
Thank you very much for help!
Quick answer:
Front end:
// Take query parameters and incorporate into a JSON queryBody
$scope.queryUsers = function(){
// Assemble Query Body
queryBody = {
longitude: parseFloat($scope.formData.longitude),
latitude: parseFloat($scope.formData.latitude),
distance: parseFloat($scope.formData.distance)
hours : Number($scope.formData.hours)
};
// Post the queryBody to the /query POST route to retrieve the filtered results
$http.post('/queryUsers', queryBody)
// Store the filtered results in queryResults
.success(function(queryResults){
console.log(JSON.stringify(queryBody));
// Pass the filtered results to the Google Map Service and refresh the map
gservice.refresh(queryBody.latitude, queryBody.longitude, queryResults);
// Count the number of records retrieved for the panel-footer
$scope.queryCount = queryResults.length;
})
.error(function(queryResults){
console.log('Error ' + queryResults);
})
};
Back end:
// Retrieves JSON records for all users who meet a certain set of query conditions
app.post('/queryUsers/', function(req, res){
// Grab all of the query parameters from the body.
var lat = req.body.latitude;
var long = req.body.longitude;
var distance = req.body.distance;
var hours = req.body.hours
var dateNow = new Date(); //right now
// Opens a generic Mongoose Query. Depending on the post body we will...
var query = User.find({});
// ...include filter by Max Distance (converting miles to meters)
if(distance){
// Using MongoDB's geospatial querying features. (Note how coordinates are set [long, lat]
query = query.where('location').near({ center: {type: 'Point', coordinates: [long, lat]},
// Converting meters to miles. Specifying spherical geometry (for globe)
maxDistance: distance * 1609.34, spherical: true});
}
console.log(dateNow);
dateNow.setHours(dateNow.getHours()- hours); // XX hours from now
console.log(dateNow);
query = query.where('created_at').gte(dateNow); //gte - greater then equal
// Execute Query and Return the Query Results
query.exec(function(err, users){
if(err)
res.send(err);
// If no errors, respond with a JSON of all users that meet the criteria
res.json(users);
});
});
Sorry if I am misunderstanding your question but just I want to give you some tips, this query looks like a GET instead of a POST, and you can use query params or path params.
Front end:
$http.post('/recentUsers?numHours=24', queryBody)
Back end:
var numberOfHours;
if (req.query.numHours) {
try {
numberOfHours = parseInt(req.query.numHours)
} catch(e) {}
}
numberOfHours = numberOfHours || 24; // default to 24 hours.
dateNow.setHours(dateNow.getHours() - numberOfHours)
Well, if you are going to subtract always a number X of hours, first I would recommend to change the name of your webService like : queryUsersFromLastNHours
Supposing you are going to trigger that request through a button click, then you may use a call like this
<button id='myButton' ng-click="queryUsersFromLast24Hours()">MyButton</button>
<input id="numberOfHours" ng-bind="hoursToSubtract" />
In angularJs, you must bind that type of values to the Controller via $scope. Then you will have in your Controller a fuction like this
$scope.hours = 0;
var $scope.formData.hours = function() {
var hours = $scope.hours;
var queryBody = {
longitude: parseFloat($scope.formData.longitude),
latitude: parseFloat($scope.formData.latitude),
distance: parseFloat($scope.formData.distance),
hoursToSubtract: hours
};
$http.post('/queryUsersFromLast24Hours', queryBody) ....
}
Read the ngBind documentation for a better understanding
And finally in your nodeJs code, change
dateNow.setHours(dateNow.getHours()-24);
for
var n = req.body.hoursToSubtract;
if (n != null) {
dateNow.setHours(dateNow.getHours()-n);
}

Parse Multiple doesNotMatchKeyInQuery

I am having a problem using Parse queries in javascript. I want to try and use multiple doesNotMatchKeyInQuery functions but it only allows the last one to be used. Any ideas how I can make code like this work? Ignore the errors that might exist in other parts of the code. I wrote this as an example
//Query 1
var Class1 = Parse.Object.extend("Class1");
var class1Query = new Parse.Query(Class1);
class1Query.equalTo("id", id1);
//Query 2
var Class2 = Parse.Object.extend("Class2");
var class2Query = new Parse.Query(Class2);
class2Query.equalTo("id", id2);
//Query 3
var Class3 = Parse.Object.extend("Class3");
var class3Query = new Parse.Query(Class3);
class3Query.equalTo("id", id3);
//Bringing it all together
var finalQuery = new Parse.Query("User");
//This is the part below I am talking about
finalQuery.doesNotMatchKeyInQuery("objectId", "id1", class1Query);
finalQuery.doesNotMatchKeyInQuery("objectId", "id2", class2Query);
finalQuery.doesNotMatchKeyInQuery("objectId", "id3", class3Query);
finalQuery.find({
success: function (results) {
response.success(results);
},
error: function (error) {
response.error(error);
}
});
It's not possible to do such a complex query in a single request. However, you can fetch the keys you don't want to match ahead of time, and construct a secondary query from that.
I've written up an example based upon your code above:
// Assuming we're actually dealing with 3 different classes,
// and these can't be combined into a single query
var class1Query = new Parse.Query('Class1');
class1Query.equalTo('id', id1);
var class2Query = new Parse.Query('Class2');
class2Query.equalTo('id', id2);
var class3Query = new Parse.Query('Class3');
class3Query.equalTo('id', id3);
// Fetch the results from all three queries simultaneously
Parse.Promise.when([
class1Query.find(),
class2Query.find(),
class3Query.find()
]).then(function(results) {
// results will contain three arrays of results
// We can now build a query where the objectId is not equal
// to any of the objectIds of the results
var ids = [];
results.forEach(function(set) {
set.forEach(function(obj) {
ids.push(obj.id);
});
});
return new Parse.Query('FinalClass').notContainedIn('objectId', ids).find();
})
I want to caution you that this query will not be efficient for large sets of data. "Does not equal" queries are never fast, because they have to loop over every object in the table. If there is another way to get your data, I highly encourage it.

Categories

Resources