can't make nodejs mysql query results a global variable - javascript

I'm trying to use the mysql module to get some data from a mysql database and then write it to an HTML page but it seems stuck inside the query function itself.
The code looks like this:
rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
var rooms = result;
console.log(rooms[9]);
});
});
console.log(rooms);
The first console.log outputs the results properly, but the second one returns the empty array as declared in the first line and prints first. I'm new to Javascript so I'm probably missing something very obvious. Thanks in advance.

I think you are recreating another variable because adding "var " before. Have you tried without it?
If it doesn't work, here another posible solution:
global.rooms = [];
global.rooms = result;
https://nodejs.org/api/globals.html#globals_global

var rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
rooms = result;
console.log(rooms[9]);
});
});
console.log(rooms);
you missed out to declare rooms as global variable.

approach using a callback function
rooms = [];
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "MYUSERNAME",
password: "MYPASSWORD",
database: "travel"
});
function query(callback) {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM rooms", function (err, result, fields) {
if (err) throw err;
var rooms = result;
callback(rooms);
console.log(rooms[9]);
});
});
}
function log_it_out() {
console.log(rooms);
}
query(log_it_out);

I don't think it matters for you anymore since it's been roughly a year since you asked this basic question, however maybe someone else that searches for this question might find this information helpful since I had the same problem.
**} else if(req.url === "/api/labeat") {
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(information));**
IMPORTANT
When you try to return something to a website beside the variable declarations, when you use res.end();, make sure to turn the result or whatever kind of information you're trying to work with into a string or buffer since the res.end() expects either a string or a buffer. Also specify the Content-Type as I did (application/json).

Related

SQL SELECT FROM with multiple variables

I would like to make a SELECT FROM request, and instead of having the name of the column ( which is Alan), I would like to replace it by a variable ( which is the variable named pseudo), I know it can be done in php, but i am trying to do it in javascript using Node.js.
I have tried to replace the name og the column but the result in the console is wrong.
there are no error messages, but the data shown in the console is empty, it shows just an empty parenthesis.
var pseudo = "Alan";
var onlinepeers = "Sarah";
var mysql = require('mysql');
let connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "espace_membre"
});
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT ALan FROM matches WHERE Alan = '" + onlinepeers + "'", function(err, result) {
if (err) throw err;
console.log(result);
});
});
You can try something Like this,Using template literals
var pseudo = "Alan";
var onlinepeers = "Sarah";
var mysql = require('mysql');
let connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "espace_membre"
});
connection.connect(function(err) {
if (err) throw err;
connection.query(`SELECT Alan FROM matches WHERE ${pseudo}=${onlinepeers}`, function (err, result) {
if (err) throw err;
console.log(result);
});
});
Better Use Parametriezed Query
let sql=`SELECT Alan FROM matches WHERE ${pseudo} =?`
connection.connect(function(err) {
if (err) throw err;
connection.query(sql,[onlinepeers], function (err, result) {
if (err) throw err;
console.log(result);
});
});
First create a queryString as follows:
let queryString = "SELECT " + pseudo + " FROM matches WHERE " + pseudo + " = .....
then:
Use the variable queryString in your connection.query(queryString)

How to run my node.js file when trigger button in html

First of all, today is my first time that i worked with node.js. So, excuse me if my questions are very simple for you.
I'm writing you because i can't find similar solutions to my problem.
I want to press an html button and then i want to trigger my test.js file.
Do you know if i can insert the following code inside my js file? Is there an another way that we run the node.js files inside html?
Here is my code: (by the way is right the window redirection??)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "",
database: "testaki1"
});
con.connect(function(err) {
if (err) throw err;
var someVar = [];
con.query("SELECT site_id FROM testaki12 WHERE user_id = '5'", function (err, rows) {
if (err){
throw err;
}
else {
setValue(rows);
}
});
function setValue(value) {
someVar = value;
console.log(someVar);
}
if (someVar == 1)
{
res.send('<script>window.location.href="https://www.google.gr/?hl=el";</script>');
}
});

How do I send data from MySQL database connected to a Node.js server so that I can use it for client side JavaScript?

To preface, I'm completely new to NodeJs and MySQL.
I have a website running on Node with express like this
var express = require('express');
var app = express();
var path = require("path");
var mysql = require("mysql");
app.use(express.static('Script'));
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "blocks"
});
con.connect(function(err){
if(err) throw err;
console.log("connected!");
con.query("SELECT * FROM blockchain", function(err, result, fields){
if(err) throw err;
console.log(result);
});
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
It's connected to the server successfully, and can print out the server values on my command prompt.
Is there a way to send this data to my website such that I can use the values for client side scripting? For example, I want a create a new <p> element in my index.html file to represent every entry in the database, and thus alter my websites displayed information.
So if the database was empty, my website would look empty. If the database had three entries, my website would have 3 <p> elements that corresponded to the inputs of the three entries.
To easy. At first we open the db connections:
con.connect(function(err){
if(err) throw err;
console.log("connected!");
Then if the connection is set up, we can start answering requests:
app.get("/", (req, res) => {
Now when a request comes in, we get the latest data from the db:
con.query("SELECT * FROM blockchain", function(err, result, fields){
if(err) return res.end("sth went wrong :(");
res.end(result);
});
});
});
Now you only need to transfer the data into html, for that i would recommend using a template engine.
When you query data from a database, it is an asyncronous operation. In other words, it takes time before you have all the data.
So in your case it sounds best to use a promise:
var mysql = require('promise-mysql');
mysql.createConnection({
host: 'localhost',
user: 'sauron',
password: 'theonetruering',
database: 'mordor'
}).then(function(conn){
var result = conn.query('select `name` from hobbits');
conn.end();
return result;
}).then(function(rows){
for (var i in rows){
document.write("<p>name[i]</p>");
}
});
The funtion after .then executes when your query has finished. Now you can sort you query with a for loop.
mysql-promise: https://www.npmjs.com/package/promise-mysql
HTML DOM write: https://www.w3schools.com/jsref/met_doc_write.asp

Javascript MySQL query returns [object Object] in Discord chat, but returns the correct result in the console

My code:
const Discord = require("discord.js");
var mysql = require('mysql');
exports.run = (client, message) => {
var con = mysql.createConnection({
host: "******",
user: "******",
password: "******",
database: "*******"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT ActivationKey FROM whitelists WHERE DiscordID = '" + message.author.id + "'", function (err, rows, fields) {
if (err) throw err;
console.log(rows);
message.channel.send(rows);
});
};
);
};
The Discord Chat Output https://imgur.com/vzUXNbA
The Console Output https://imgur.com/8zUxvIJ
The MySQL Setup https://imgur.com/GJoUuY7
Any help would be greatly appriciated. Please point out even the most obvious, I'm sort of new to Javascript.
I know I'm probably being an idiot, but this issue is really frustrating me and hindering my progress.
Thanks,
Timothy
You have to extract what you need to from rows that seems an array of objects:
rows rapresentation:
[
{
ActivationKey : "WWWW-XXXX-YYYY-ZZZZ"
}
]
You can try with this code:
message.channel.send(rows[0].ActivationKey);
You should be able to use the util package to log the object in depth
const util = require('util')
console.log(util.inspect(myObject))

Passing Object with module exports

I am still new to nodejs and Javascript, I am sorry if my question appear to be very simple but I am struggling a lot and I can't seem to find an answer on the net.
What I want to do is basically calling a script (sqlRequest.js) and send an integer while calling it. This script will send an sql request to my database and will return the result (an object) to the original file.
Here are the codes:
router.post('/request', function(req, res, next){
var id = req.body.id;
var essai = require('./sqlRequest.js');
console.log("INDEX: "+essai.sendSQL(id)); });
And now the sqlRequest.js code:
exports.sendSQL = function(id) {
var mysql= require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'bcombes',
password : 'bertrand1994',
database : 'totalkpi'
});
connection.connect();
var sql ="SELECT * FROM tra_ticket where id=?";
var insert=[id];
sql=mysql.format(sql, insert);
connection.query(sql, function(err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
return rows;
}
});};
On the console I can see that the console.log("INDEX: "+essai.sendSQL(id)); appears to be undefined and is displayed before the console.log(rows).
Is it possible that the server does not wait for the function to finish and display the variable anyway ?
Anyway thank you for taking the time to help.
Your logic to pass a variable between files is fine. The reason your seeing essai.sendSQL(id) return undefined is because connection.query(...) is called asynchronously and, as you've mentioned in your question, the console.log fires before the DB query completes.
To fix that issue you just need to refactor your code slightly:
var essai = require('./sqlRequest.js');
router.post('/request', function(req, res, next){
var id = req.body.id;
// send callback to sendSQL
essai.sendSQL(id, function(index) {
// this will only fire once the callback has been called
console.log("INDEX: " + index)
})
});
And then in sqlRequest.js:
exports.sendSQL = function (id, cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'bcombes',
password: 'bertrand1994',
database: 'totalkpi'
});
connection.connect();
var sql = "SELECT * FROM tra_ticket where id=?";
var insert = [id];
sql = mysql.format(sql, insert);
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
// call the callback
cb(rows);
}
});
};

Categories

Resources