Variable as table name in node.js mysql - mysql

I use node.js and mysql module.When I execute the following code I want the table_name to be set to a variable, not a static table name. For example I want table_name to be todays date.
connection.query(
"CREATE TABLE `<table_name>` (" +
" `title` varchar(50) NOT NULL,"+
" `text` varchar(50),"+
" `created` timestamp NULL,"+
" PRIMARY KEY (`title`));"
);
Is it possible to set table name as a variable in mysql module for node.js?
Best Regards

The module has built in methods to handle your case, you need to escape the variables like this:
var tableName = 'THETABLE';
connection.query('CREATE TABLE ?? (column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size))', [tableName], function (error, results) {
// error will be an Error if one occurred during the query
// results will contain the results of the query (if any)
});
You can read more about this feature here:
https://github.com/felixge/node-mysql/#escaping-query-identifiers

async function createTable(db_connection,tableName) {
await new Promise((resolve, reject) => {
db_connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
db_connection.query('CREATE TABLE ?? (doc_source_type varchar(255) default null,
doc_id varchar(255) default null, company varchar(255) default null)',
[tableName],
function(err, results) {
if (err) {
console.log(err.message);
reject(err);
}
else{
console.log("Table created successful");
resolve(results);
}
});
});
});
}
or you can even try different approach
async function setTable(db_connection,tableName) {
await new Promise((resolve, reject) => {
db_connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
let createTodos =`create table if not exists ??(
id int primary key auto_increment,
doc_id varchar(255) default null,
doc_source_type varchar(255) default null,
company varchar(255) default null,
customer varchar(255) default null,
rubric_version varchar(255) default null,
assessment_type varchar(255) default null,
indexed_at datetime default null,
assessment_date datetime default null,
industry_type varchar(255) default null
)`;
//console.log(createTodos);
db_connection.query(createTodos, [tableName], function(err, results) {
if (err) {
console.log(err.message);
reject(err);
}
else{
console.log("Table created successful");
resolve(results);
}
});
});
});
}

Related

Unable to insert to Child Table in reference of a Parent Table in node.js

I'm having a hard time figuring out what's wrong with my code base or on my database since i was just trying to insert a device information to a table in reference to the user who owns it. no errors are being thrown but the device registration isn't working.
Here's the database
CREATE TABLE `users` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`email` varchar(255),
`password` varchar(255),
`firstname` varchar(255),
`lastname` varchar(255),
`dob` varchar(255),
`country` varchar(255),
`farmname` varchar(255),
`acctype` varchar(255),
`firmware` double
);
CREATE TABLE `controlModules` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`deviceowner` int,
`devicename` varchar(255),
`serial#` varchar(255),
`devicestate` varchar(255),
`ipaddress` varchar(255),
`wanaddress` varchar(255),
`firmware` varchar(255)
);
ALTER TABLE `controlModules` ADD FOREIGN KEY (`deviceowner`) REFERENCES `users` (`id`);
Here's the function for react.js where it passes input data to backend
const email = sessionStorage.getItem("email");
const [name, setDeviceName] = useState("");
const [serial, setDeviceSerial] = useState("");
const [lanip, setDeviceLANIP] = useState("");
const [wanip, setDeviceWANIP] = useState("");
const [deviceStatus, setDeviceStatus] = useState("");
Axios.defaults.withCredentials = true;
const registerDevice =()=>{
Axios.post("http://localhost:3020/registerDevice", {
email: email,
name: name,
serial: serial,
lanip: lanip,
wanip: wanip,
}).then((response) => {
if (response) {
setDeviceStatus(response);
} else {
setDeviceStatus("error");
}
});
};
Here's the code for backend on node.js
app.post("/registerDevice", (req, res)=> {
const email = req.body.email;
const name = req.body.name;
const serial = req.body.serial;
const lanip = req.body.lanip;
const wanip = req.body.wanip;
const status = "online"
const firmware = "1.3";
console.log(email);
let stmt = `SELECT * FROM users WHERE id=?`;
let todo = [email];
//getting parentid
db.query(stmt, todo, (err, results, fields) => {
if (err) {
return console.error(err.message);
}
console.log(results)
const userid = results.id;
let statement = `INSERT INTO controlModules(deviceowner, devicename, serial#, devicestate, ipaddress, wanaddress, firmware) VALUES (?,?,?,?,?,?)`;
let task = [userid, name, serial, status, lanip, wanip, firmware];
//inserting to childtable
db.query(statement, task, (err, results, fields) => {
if (err) {
return console.error(err.message);
}
console.log(results);
});
});
Thanks for the help and enlightenment.

Operand should contain 1 column in express mysql query

Am curretly facing the following error when i try to query using express
code: 'ER_OPERAND_COLUMNS',
errno: 1241,
sqlMessage: 'Operand should contain 1 column(s)',
sqlState: '21000',
index: 0,
sql: "insert into quiz(user_pk,question,answer,choices,discussion) values (1, 'what is math', 'study of calculations', ('study of calculations', 'study of computing', 'study of books'), 'its amaizing')"
}
routes
.post((req, res) => {
query =
"insert into quiz(user_pk,question,answer,choices,discussion) values ?";
values = [Object.values(req.body)];
console.log(values)
connection.query(
query,
[values],
(err, result) => {
if (err) throw err;
res.json({ message: "question sussefully created" });
}
);
});
data i want to insert
{
"user_pk":1,
"question":"what is math",
"answer":"study of calculations",
"choices":["study of calculations","study of computing","study of books"],
"discussion":"its amaizing"
}
example of query i want to perform
insert into quiz(user_pk,question,answer,choices,discussion)
values(1,'what is physics?','study of matter','["study of matter","study of dances","study of matter"]','lorem ipsum dolor lorem');
here is the quiz table
CREATE TABLE if NOT EXISTS quiz(
quiz_pk INT NOT NULL AUTO_INCREMENT,
user_pk INT NOT NULL,
question VARCHAR(255) NOT NULL,
answer VARCHAR(255) NOT NULL,
choices JSON NOT NULL,
discussion VARCHAR(255) NOT NULL,
PRIMARY KEY (quiz_pk),
FOREIGN KEY (user_pk) REFERENCES user(user_pk)
);
please help me out.Thanks alot

SQL failed to output parameters

So we have 2 tables:
listings
users
Currently, i'm trying to retrieve all the information of the given users id where the fk_poster_id of the listings table is the foreign key with reference made to the users id by using the GET method.But when i try to execute the codes, i receive [] as the output. Is there a way to solve this?
Here's my current sql codes
DROP DATABASE snapsell;
CREATE DATABASE IF NOT EXISTS `snapsell`;
USE `snapsell`;
DROP TABLE IF EXISTS `users`;
DROP TABLE IF EXISTS `listings`;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
UNIQUE (username),
profile_pic_url VARCHAR(1000) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;
-- THESE ARE JUST EXAMPLES AND TEST KITS.TO BE REMOVED BEFORE PRESENTATION.
INSERT INTO users (username, profile_pic_url) VALUES
("steve_jobs","https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Steve_Jobs_Headshot_2010-CROP2.jpg/800px-Steve_Jobs_Headshot_2010-CROP2.jpg"),
("barack_obama","https://upload.wikimedia.org/wikipedia/commons/e/e9/Official_portrait_of_Barack_Obama.jpg"),
("kim_jung_un","https://upload.wikimedia.org/wikipedia/commons/d/d0/Kim_Jung-Un_-_Inter_Korean_Summit%28cropped%29_v1.jpg"),
("lee_kuan_yew","https://upload.wikimedia.org/wikipedia/commons/0/0f/Lee_Kuan_Yew.jpg");
CREATE TABLE listings (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
description_i VARCHAR(1000) NOT NULL,
price INT(6) NOT NULL,
fk_poster_id INT NOT NULL,
KEY fkPosterID (fk_poster_id),
CONSTRAINT FOREIGN KEY (fk_poster_id) REFERENCES users(id) ON DELETE NO ACTION ON UPDATE NO ACTION,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;
-- THESE ARE JUST EXAMPLES AND TEST KITS.TO BE REMOVED BEFORE PRESENTATION.
INSERT INTO listings (title, description_i, fk_poster_id, price) VALUES
("iPhone 6s USED","In good condition. Camera and screen not working.","2","250"),
("Samsung S7 NOT USED","In bad condition. Screen fully smashed. Can't even operate.","3","10000");
CREATE TABLE offers (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
fk_offeror_id INT NOT NULL,
KEY fkOfferID (fk_offeror_id),
CONSTRAINT FOREIGN KEY (fk_offeror_id) REFERENCES users(id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB;
SELECT * FROM users;
SELECT * FROM listings;
My current controller codes
var express = require('express');
var app = express();
const userJs = require('../model/user')
const listingJs = require('../model/listing')
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json()); //parse appilcation/json data
app.use(urlencodedParser);
app.get("/users/:user_id/listings/",(req,res) => {
var user_id = req.params.id;
userJs.getListingsByUserID(user_id, (error,results) => {
if (error) {
res.status(500).send("Internal Server Error")
}
res.status(200).send(results);
});
})
And my current user.js codes
var db = require('./databaseConfig.js')
const users = {getListingsByUserID: function (user_id, callback) {
const getListingsByUserIDQuery = 'SELECT u.id,l.title,l.description_i,l.price,l.fk_poster_id,l.created_at FROM listings l INNER JOIN users u ON u.id = l.fk_poster_id WHERE u.id = ?;';
db.query(getListingsByUserIDQuery,[user_id],(error,results) => {
if (error) {
callback(error,null);
return;
};
callback(null,results);
})
}
module.exports = users;
Just try to use Promise instead of callback like this:
const users =
{
function getListingsByUserID(user_id)
{
return new Promise((resolve, reject) =>
{
db.query(getListingsByUserIDQuery,[user_id],(error,results) =>
{
if (error)
{
return reject(error);
}
else
{
return resolve(results);
}
});
});
});
};
If you want result through callback method then try callback(null,results[0]);

How to create a MySQL schema when deploying with Heroku (Express Server)

Suppose I have the following server.js file:
server.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var dbhelpers = require('./public/database_helpers.js')
var bodyParser = require('body-parser')
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/views'));
app.use(express.static(__dirname + '/public/controlers'));
app.use(express.static(__dirname + '/public/lib'));
app.use(bodyParser())
var connection = mysql.createConnection({
**Correct info**
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
app.post('/signup',function(req,res){
var newUser = req.body;
connection.query('INSERT INTO users SET ?',newUser, function(err, rows,fields){
if (!err){
console.log("posted to database")
res.sendStatus(200);
} else{
console.log('Error while performing Query.');
res.sendStatus(500);
}
});
})
app.get('/artistsearch',dbhelpers.checkDbArtist)
app.post('/artistsearch', dbhelpers.insertDb)
app.post('/reviews',dbhelpers.insertReviewDb)
app.listen(process.env.PORT || 3000);
console.log("Listening at 3000")
I have recently deployed to heroku and used the clearDB addon since I am using MySQL. The logs indicate that I have been able to connect to the database, but the thing is that I believe Heroku creates an empty database. How can I create the following schema in my with clearDB:
schema.sql
CREATE TABLE users(
users_id INT NOT NULL AUTO_INCREMENT,
user_username VARCHAR(100) NOT NULL,
user_password VARCHAR(40) NOT NULL,
PRIMARY KEY ( users_id )
);
CREATE TABLE artist(
artist_id INT NOT NULL AUTO_INCREMENT,
artist_name VARCHAR(100) NOT NULL,
artist_genre VARCHAR(100) NOT NULL,
artist_imageurl VARCHAR(100) NOT NULL,
artist_bio VARCHAR(1000) NOT NULL,
PRIMARY KEY ( artist_id )
);
CREATE TABLE reviews (
review_id INT NOT NULL AUTO_INCREMENT,
user_name VARCHAR(100) NOT NULL,
venue VARCHAR(100) NOT NULL,
number_of_stars INT NOT NULL,
review_details VARCHAR(10000) NOT NULL,
artist_id VARCHAR(100) NOT NULL,
PRIMARY KEY ( review_id )
);
Anyone had any idea?
First, you should type heroku config to get your clearDB credentials.
Then, you can ran this command from your terminal : mysql --host=us-cdbr-east.cleardb.com --user=xxxx --password=xxxx --reconnect heroku_xxxxxx < schema.sql

How can i display fetched mysql data into HTML dropdown list in NodeJS?

hey i am total new in node.js..
Can U any one please Explain me step by Step how i can display values into dropdownlist.. i have just create a single file.. File name is fetch.js
which get(fetch) all the values from mysql.. in the form of JSON.. here is my code..
var http = require('http');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : 3306, //port mysql
user : 'root',
password: '',
database: 'node_js'
});
console.log('MySQL Connection details '+connection);
http.createServer(function (request, response)
{
console.log('Creating the http server');
connection.query('SELECT * FROM `emp` where Branch="PHP"', function(err, rows, fields)
{
console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});
response.end(JSON.stringify(rows));
response.end();
});
}).listen(8084);
my database
CREATE TABLE IF NOT EXISTS `emp` (
`ID` int(5) NOT NULL AUTO_INCREMENT,
`Name` varchar(25) NOT NULL,
`Address` varchar(25) NOT NULL,
`Branch` varchar(25) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
please help me in this
Thanks in Adv.