I am trying to insert data into the MySQL user table through node js, I am using
and following
https://github.com/felixge/node-mysql#escaping-query-values
Below is my code, I don't really know what went wrong, I couldn't insert data through postData query, but it works if I try to execute the test query.
Why isn't the postData query working?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : 3306,
database : 'csc309',
user : 'root',
password : 'root'
});
connection.connect();
var postData = {username: 'user4',
firstname: 'first',
lastname: 'last',
password: 'password',
email: 'test2#email.com'};
/*
var test = connection.query('INSERT INTO user (username, firstname, lastname, password, email) VALUES
("user4", "first", "last", "password", "sdfsdf#hotmail.com")');
*/
var query = connection.query('INSERT INTO user VALUES ?', postData, function(err, result) {
console.log('The solution is: ', result);
});
Here is my user sql user table.
create table user (
id int AUTO_INCREMENT PRIMARY KEY,
username varchar(40) UNIQUE NOT NULL,
firstname varchar(40) NOT NULL,
lastname varchar(40) NOT NULL,
password varchar(100) NOT NULL,
created_at datetime NOT NULL,
email varchar(40) UNIQUE NOT NULL,
reputation int DEFAULT 0,
mailing_address varchar(100),
phone varchar(20),
gender varchar(10),
admin tinyint default 0 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
If you want to insert a row with explicitly specified values passing an object to a escaped query, you should use the INSERT ... SET form:
var query = connection.query('INSERT INTO user SET ?', postData, function(err, result) {
console.log('The solution is: ', result);
});
The resulting query will look like:
INSERT INTO user SET `username` = 'user4', `firstname` = 'first', `lastname` = 'last', `password` = 'password', `email` = 'test2#email.com'
Related
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.
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
I'm a nodeJS beginner and am trying to learn it by creating a blog. To do so, I have three tables
CREATE TABLE `articles` (
`article_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` longtext NOT NULL,
`image` varchar(255) NOT NULL,
`created` datetime NOT NULL,
`author_id` int(11) NOT NULL,
PRIMARY KEY (`article_id`)
)
CREATE TABLE `authors` (
`author_id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`author_id`)
)
CREATE TABLE `comments` (
`comment_id` int(11) NOT NULL AUTO_INCREMENT,
`comment_content` longtext NOT NULL,
`created` datetime NOT NULL,
`comment_author` varchar(255) NOT NULL,
`id_article` int(11) NOT NULL,
PRIMARY KEY (`comment_id`)
)
On my page, I want to get all my articles, with their associated authors and comments.
This is my node code to get the data :
app.get('/api/articles', function(req, res){
connection.query('SELECT * FROM articles LEFT JOIN authors ON articles.author_id = authors.author_id LEFT JOIN comments ON articles.article_id = comments.id_article', function(err, row, fields){
if(!err){
res.json(rows);
}else
console.log('Error');
});
});
This query returns the data I need, but I want to parse it to get something that I can use easier in the front part, like
[
{
article_id: 1,
content: 'test',
title: 'test',
image: '',
author: {
author_id: 1,
email: 'test#test.com'
},
comments: [
{
comment_id: 1,
comment_content: 'test',
comment_author: 'test'
},
{
comment_id: 2,
comment_content: 'test',
comment_author: 'test'
}
]
}
]
Instead of the current return that looks like
[
{
article_id: 1,
title: 'test',
content: 'test',
image: '',
author_id: 1,
email: 'test#test.com',
comment_id: 1,
comment_content: 'test',
comment_author: 'test
}
]
I spent some time looking for something to do it, but couldn't find anything, so if someone knows how to do it, I'd be very grateful.
Thanks
You'll need to do two things:
(1) make sure you are sorting by article_id in your query
(2) create a tiny state machine, keeping track of the article_id, and loop through each record aggregating the comments. if your article_id changes, write the record to the table and move on to the next article:
var table = [];
var lastid = -1;
var article = {};
for(var i=0;i<rows.length;i++) {
var row = rows[i];
if (row.article_id!==lastid) {
//The id has changed, so create a new article
if (article.article_id) {
//If this isnt the first time looping, add the last article to the table
table.push(article);
}
article = {};
//create the structure you want
article.article_id = row.article_id;
article.title = row.title,
article.content = row.content,
article.image = row.image,
article.author = {
author_id: row.author_id,
email: row.email,
};
//comments go in this array. add the first one
article.comments = [{
comment_id:row.comment_id,
comment_content:row.commment_content,
comment_author:row.comment_author
}];
} else {
//same article, new comment
article.comments.push({
comment_id:row.comment_id,
comment_content:row.commment_content,
comment_author:row.comment_author
})
}
//update the id to check against the next row
lastid = row.article_id;
}
//make sure you push on the last article
table.push(article);
//Now you can send back the table in the new structure...
return table;
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
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.