SQL SELECT FROM with multiple variables - javascript

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)

Related

How can I access the result of a SQL request in NodeJS?

How can I access the result of a SQL request in JavaScript and store it in a variable?
SELECT COUNT(*) FROM account where username='Mashiro';
+----------+
| COUNT(*) |
+----------+
| 9 |
+----------+
My code:
con.connect(function(err) {
if (err)throw err;
var sql = ("SELECT COUNT(*) FROM account where username=?");
con.query(sql,[username],function (err, result){
if (err)throw err;
console.log(result);
var x = ???????????
return result;
})
})
}
I'd like set the x variable to '9' like in the following:
console.log(x); >>> 9
Select With a Filter
When selecting records from a table, you can filter the selection by using the "WHERE" statement:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT COUNT(*) FROM customers WHERE username = ?", [$username], function (err, result) {
if (err) throw err;
console.log(result);
});
});
More examples : https://www.w3schools.com/nodejs/nodejs_mysql_where.asp
More examples with prepare statements and more : https://evertpot.com/executing-a-mysql-query-in-nodejs/
Like this i think it should work:
con.connect(function(err) {
if (err)throw err;
var sql = ("SELECT COUNT(*) AS count FROM account where username=?");
con.query(sql,[username],function (err, result){
if (err)throw err;
console.log(result[0].count);
var x = result[0].count;
return result;
})
})
}

How to query a mysql database with Node.js to get specific users (fields) by name in url, not only by ID

I know how to query a SQLite Database with Node.js to bring back a specific key with the corresponding field information but I am unable to find the right syntax to do it in Mysql.
I want to put a specific station name in the url such as and result all its information from the database. example. http://localhost:5000/station/
The database result would be:
["station":"winton", "location":"123 Byers Lane", "property size":"3000"]
<sqlite> needs to be put in <mysql>
app.get('station/:stationid', req, res) => {
const stationToLookup = req.params.stationid;
db.all (
'SELECT * FROM stores WHERE station = $station',
{
$station = stationToLookup
},
(err, rows) => {
console.log(rows);
if (rows.length > 0){
res.send (rows[0]);
}else{
res.send({});
}
});
});
You should install mysql driver first via npm. npm install mysql
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
app.get('station/:stationid', req, res) => {
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM stores WHERE station ='" + req.params.stationid + "'", function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
NOTE how the double quotes and single quotes have been used in the code above. The query is inside double quotes and then the value of a field which we are going to find is between single qoutes embedded inside double qoutes just after the = sign.
Here seems to be a solutioin.....#James #SonuBamniya
//(2)getting all stations names
app.get('/stationNames/:stationid',(req,res)=>{
const nameToLookup = req.params.stationid;
//console.log(nameToLookup);
db.query('SELECT * FROM stores WHERE station = ?', [nameToLookup],(err, rows, fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});

Node.js module export "pre-load"

This is in a mysql.js file:
const mysql = require('mysql');
const config = require('./config.json');
const con = mysql.createConnection({
host: config.dbhost,
user: config.dbuser,
password: config.dbpass,
database: config.dbname,
});
module.exports = {
findUser: function(email) {
const sql = 'SELECT * FROM users WHERE email = ' + mysql.escape(email);
con.connect(function(err) {
if (err) throw err;
console.log('Connected!');
con.query(sql, function(err, result) {
if (err) throw err;
return result[0].id;
});
});
},
};
then within my index.js file there is this:
const mysql = require('./mysql.js');
console.log(mysql.findUser('example#example.test'));
When the code is running, it outputs "undefined" and then "Connected!" after the db connection is made. Even though if I do a console.log on result[0].id it outputs 1, which is the correct id...
Question: How can I load the mysql.js file first before the function is called?
You need to wait for response cause its an asynchronous function.
Try using callback or promises.
Callback example:
mysql.findUser('example#example.test', function(res)){ console.log(res)});
module.exports = {
findUser: function(email, callback) {
const sql = 'SELECT * FROM users WHERE email = ' + mysql.escape(email);
con.connect(function(err) {
if (err) throw err;
console.log('Connected!');
con.query(sql, function(err, result) {
if (err) throw err;
callback(result[0].id);
});
});
},

How to insert json data into mysql using node js

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 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");
I'm getting the error
throw err; // Rethrow non-MySQL errors
^
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' 3 ports - multi device charging', 'Universal Voltage', 'Best Price Ever', 'Ext' at line 1
When doing a prepared statement, you need a ? for each of the values you bind. E.g. INSERT INTO offers (description,start_time,end_time) VALUES (?, ?, ?, ?)
It might be worthwhile to take a look at using something like the knex.js module. It uses the mysql module underneath and does the sql binding under the hood.

can't make nodejs mysql query results a global variable

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).

Categories

Resources