I'm trying to figure out how I can make a global variable that can grab from a mysql table.
app.get('*', function(req, res, next){
res.locals.user = req.user || null;
res.locals.mobs = db.query('SELECT * FROM mobs', function(err, rows){
var rowLength = rows.length;
for (var i = 0; i < rowLength; i++) {
var mobs = rows[i];
}
});
The mobs ones is what I am trying to do. using <%= mobs[0].name %> produces a a cant get from undefined.
I think you need this
db.query('SELECT * FROM mobs', function(err, rows){
res.locals.mobs = rows
});
if you want pass the data to template try this
db.query('SELECT * FROM mobs', function(err, rows){
res.render('view.ejs',{mob:rows})
});
I found an answer! I am not sure if it is the most efficient, but here it is:
app.use(function(req, res, next) {
res.locals.errors = null;
// Mob Database
db.query('SELECT * FROM mobs', function(err, rows){
req.mobs = rows;
res.locals.mobs = req.mobs;
});
next();
});
Related
I'm trying to complete 2 select with 2 different SQL Server queries in the same HTML.
I'm using this code to complete 1
router.js
app.get('/bajatel', function(req, res, next) {
var data = []
request.query('select NLineas from tb_lineas', function(err, fields){
if(err) {
console.log('error en la busqueda');
return;
}
console.log(fields)
// Pass the DB result to the templates
for (var i = 0; i < fields.recordset.length ; i++){
data.push({NLineas: fields.recordset[i]})
}
res.render('bajatel.html', {Valuelist: data});
console.log(data)
});
});
db.js
var sql = require('mssql');
var config = {
user : 'sa',
password : 'xxxxxxxx',
server : 'xxxxxxxx',
database : 'db_test'
};
var connection = sql.connect(config, function(err) {
if (err){
throw err ;
} else{
console.log('connected');
}
});
module.exports.connection = connection;
I want to add a second query in the app.get to have a second array:
var motivo = []
request.query('Select DescMotivo from tb_Motivos', function(err, rows){
if(err){
console.log('error en la busqueda');
return;
}
for (var i = 0; i < rows.recordset.length; i++){
motivo.push({DescMotivo: rows.recordset[i]})
}
The final render should be:
res.render('bajatel.html',{Valuelist: data, Motivolist: motivo})
but I don't know how to export the data to complete the array outside of the query.
the idea is to have 2 boxes with the queries options and they must select the default values
Could somebody help me?
The nodejs code below works fine when used to retrieve content from database. now when i tried to get content via pagination as per code below via prepared query statement
db.query('SELECT * FROM posts1 limit row=?, rowperpage=?', [parseInt(row),parseInt(rowperpage)], function (error, results, fields) {
});
it returns error "cannot read property forEach of undefined"
below is the full code
exports.display = function (req, res) {
var row = 0;
var rowperpage = 3;
console.log(row);
console.log(rowperpage);
var objs1 = [];
db.query('SELECT * FROM posts1 limit row=?, rowperpage=?', [parseInt(row),parseInt(rowperpage)], function (error, results, fields) {
// db.query('SELECT * FROM posts1', function (error, results, fields) {
results.forEach(function(row) {
var id = row.id;
var title = row.title;
var content = row.content;
var shortcontent = row.content;
var link = row.link;
objs1.push({
id: id,
title: title,
shortcontent: shortcontent,
content: content,
link: link,
});
});
res.end(JSON.stringify(objs1));
});
}
Adding the following code below, solve the issue
//parse int Convert String to number
let startNum = parseInt(row);
let LimitNum = parseInt(rowperpage);
var objs1 = [];
db.query("SELECT * FROM ?? limit ? offset ?", ["posts1",LimitNum,startNum], function (error, results, fields) {
Thanks
var express = require('express');
var app=express();
var length;
var affiliate = require('flipkart-affiliate');
var url = require('url');
var moment=require('moment');
var mysql = require('mysql');
var body;
var getUrl;
var product;
var offer;
var offer1;
var offer2;
var offer3;
var test1;
var test2;
var test3;
var title=[];
var description=[];
var startTime=[];
var endTime=[];
var json={};
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'coupontest'
});
var client = affiliate.createClient({
FkAffId: 'anandhkum',
FkAffToken: 'eb030998c556443087d3b1a27ac569d0',
responseType: 'json'
});
client.getCategoryFeed({
trackingId: 'anandhkum'
}, function(err, result,getUrl){
if(!err){
body=JSON.parse(result);
getUrl=body.apiGroups.affiliate.apiListings.food_nutrition.availableVariants["v1.1.0"].get;
client.getProductsFeed({
url: getUrl
}, function(err, result){
if(!err){
}else {
console.log(err);
}
});
}
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.get('/',function (req,res) {
client.getAllOffers(null,function(err, resp) {
if (!err) {
offer = JSON.parse(resp);
test1 = offer.allOffersList.length;
res.send(offer);
for(var i=0;i<test1;i++){
description[i]=offer.allOffersList[i].description;
startTime[i]=offer.allOffersList[i].startTime;
endTime[i]=offer.allOffersList[i].endTime;
}
var stmt = "INSERT INTO offers(description,start_time,end_time) VALUES (?, ?, ?)";
connection.query(stmt, [description,startTime,endTime], function (err, result) {
if (err) throw err.message;
console.log("Number of records inserted: " + result.affectedRows);
});
}
else {
console.log(err);
}
});
});
app.listen(3000);
console.log("Listening to port 3000");
the code is about getting the offer details as json data from flipkart.com and store it into the mysql table.
But I'm getting the error
throw err; // Rethrow non-MySQL errors
ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1
I tried using many sql syntax but it's showing the above error
Can anyone help me on solving the above error?
Try doing it this way, as I can see you want to insert multiple result at once so need to pass an array values which I have made in following query also the error "ER_WRONG_VALUE_COUNT_ON_ROW" is due to incorrect no of ? that you were passing in the query as you need to insert multiple no of rows so you need to make sure you get correct ? count.
var queryString = "";
var insertString = "(?,?,?),";
var values = [];
for(var i=0;i<test1;i++){
description[i]=offer.allOffersList[i].description;
startTime[i]=offer.allOffersList[i].startTime;
endTime[i]=offer.allOffersList[i].endTime;
values.push(description[i],startTime[i],endTime[i]);
queryString = queryString + insertString;
}
queryString = queryString.substring(0, queryString.length - 1); // is used to remove last ',' which will get inserted while we are creating queryString
var stmt = "INSERT INTO offers(description,start_time,end_time) VALUES " + queryString ;
connection.query(stmt,values, function (err, result) {
if (err) throw err.message;
console.log("Number of records inserted: " + result.affectedRows);
});
var sender_username = req.session.user_id;
var recipient_username = req.body.recipient_username;
var content = req.body.content;
var sql = ' SELECT sender_username, recipient_username, COUNT(recipient_username) as count FROM message WHERE sender_username = "'+sender_username+'" AND recipient_username = "'+recipient_username+'" GROUP BY sender_username LIMIT 1 ';
var message_no = 0;
var data;
connection.query(sql, function(err, result) {
if (err) {
res.send(err);
}
else {
data = result;
// res.send(data); < - this works
// res.send(result); <- this works
// res.send(result.count); <- undefined
}
});
res.send(data); // undefined (can't seem to save to variable after connection.query())
The res.send(result); seems to work. It gives:
[{"sender_username":"sender","recipient_username":"recipient","count":2}]
I am just trying to get the value for count and save that to a variable, but things like result.count are returning undefined for some reason.
It's because the JSON is an array, so you should access it like the following
res.send(result[0].count);
I m using the node,express,mysql2 packages .When i m using console.log(rows) ,it is giving me following output:
[{"userid": "test","password": "test"}]
And here is my Code :
var application_root = __dirname,
express = require("express"),
mysql = require('mysql2');
path = require("path");
var app = express();
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123',
database: "bbsbec"
});
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
connection.query('SELECT * from pass', function(err, rows) {
res.json(rows);
console.log(rows);
});
I just want to know that how can i parse this "rows" object so that i can retrive both userid and password .
[{"userid": "test","password": "test"}]
This is an Array of Objects. So: First loop over the array to get a single object and then extract its properties:
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
console.log(row.userid);
}
Try this (this is really basic):
connection.query('SELECT * from pass', function(err, rows) {
res.json(rows);
var user = rows[0].userid;
var password= rows[0].password;
});
connection.query('SELECT * from pass', function(err, rows) {
data = rows[0];
let user = data.userid;
let password= data.password;
res.json(rows);
});