use nodejs to query mysql database - javascript

I use mysql module nodejs-mysql
I have two tables, Their struct is like this:
Table nicks
id |nick |
--------------
1 |Arnold |
2 |Bob |
Table order
nick |money |
---------------
Arnold |12 |
Arnold |43 |
Arnold |3 |
Bob |32 |
Bob |2 |
I want get a json object whose struct is like this:
[
{id:1, nick:'Arnold', order:[{money:12},{money:43},{money:3}]},
{id:2, nick:'Bob', order[{money:32},{money:2}]}
]
so what should I do?I use nodejs
what I have try:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
db : 'db'
user : 'user',
password : 'secret'
});
connection.connect();
connection.query('select * from nicks',function(err,data){
//here I travese the data array,and select the order table to get the money filed data.
});
I know how to create a query with node.js, I just don't know a method to get the results I want.I don't know how to make a proper query.

Here's another solution:
var mysql = require('mysql');
var conn = mysql.createConnection({
host : 'localhost',
database : 'test',
});
var query = ' \
SELECT id, nicks.nick, GROUP_CONCAT(money) AS money \
FROM nicks, orders \
WHERE orders.nick = nicks.nick \
GROUP BY id';
conn.query(query, function(err, rows, fields) {
rows.forEach(function(row) {
row.order = row.money.toString().split(',').map(function(value) {
return { money : Number(value) };
});
delete row.money;
});
// as an example, we'll print the object as JSON
console.log(JSON.stringify(rows, null, 2));
});

Follow the documentation at https://github.com/felixge/node-mysql
You need to setup a connection and query the db
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret'
});
var queryString = "SELECT * FROM nicks n JOIN order o ON n.nick=o.nick";
connection.query(queryString, function(err, rows) {
var outputJSON = [];
for row in rows{
outputJSON.push(row);
}
return outputJSON.toJSON()
});
You need to implement the function toJSON that formats your output by picking only the desired fields you need for you JSON

Related

How to avoid duplicated random id selection in MySQL?

I need to select two unique random id from table nodes and insert it in parent column in edges table.
But problem is that they are sometimes duplicated and it need them to be always different, how could I avoid that, please?
the code:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'DAGtest3'
});
connection.connect((err) => {
if (err) throw err;
console.log('Database Connected!');
});
var a = "INSERT INTO `edges` (`parent`, `child`) VALUES ((SELECT `id` FROM `nodes` ORDER BY rand() LIMIT 1 ) , (4) )";
connection.query(a, (err, res) => {
if(err) throw err;
console.log("1 edge inserted to previous data");
});
var b = "INSERT INTO `edges` (`parent`, `child`) VALUES ((SELECT `id` FROM `nodes` ORDER BY rand() LIMIT 1) , (4) )";
connection.query(b, (err, res) => {
if(err) throw err;
console.log("Another edge inserted to previous data");
});
code for the tables:
CREATE TABLE nodes (
id INTEGER NOT NULL AUTO_INCREMENT,
sensorvalue VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
CREATE TABLE edges (
parent INTEGER NOT NULL REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE,
child INTEGER NOT NULL REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE,
PRIMARY KEY (parent, child)
);
CREATE INDEX parent_idx ON edges (parent);
CREATE INDEX child_idx ON edges (child);
Thanks in advance.
You don't want two sequential random selections, since there's a non-zero chance that the second random selection could return the same row as the first. I think you should just fetch both rows at once:
INSERT INTO `edges` (`parent`, `child`) SELECT `id`, 4 FROM `nodes` ORDER BY rand() LIMIT 2;
So, your code would just have one query to execute, instead of two:
var a = "INSERT INTO `edges` (`parent`, `child`) SELECT `id`, 4 FROM `nodes` ORDER BY rand() LIMIT 2";
connection.query(a, (err, res) => {
if(err) throw err;
console.log("2 edges inserted to previous data");
});
When I set up your DB locally and run the above code, I get a successful insert:
Database Connected!
2 edges inserted to previous data
When I query the DB in the console I get:
mysql> select * from edges;
+--------+-------+
| parent | child |
+--------+-------+
| 2 | 4 |
| 3 | 4 |
+--------+-------+
2 rows in set (0.00 sec)

Error in UPDATING thorugh mysql npm package

I am trying to UPDATE mysql Database through mysql npm package. I am using express.I need help with the following query.
app.put("/api/movies/:id", (req, res) => {
let id = parseInt(req.params.id);
let values = [...Object.values(req.body)];
values.push(id);
let fields = 'SET Rank = ?, SET Title = ?, SET Description = ?, SET Runtime = ?,\
SET Genre = ?, SET Rating = ?, SET Metascore = ?, SET Votes = ?,\
SET Gross_Earning_in_Mil = ?, SET Director = ?, SET Actor = ?, SET Year = ?';
connection.query("UPDATE moviesList " + fields + " \
WHERE Id = ?", values , (err, rows) => {
if(err) {res.send(err); console.log(err);}
else res.send(rows.message);
});
})
I was able to insert into table but I am getting following error for above code while UPDATE,
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage:
'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 \'SET Title = \'Pulp Fiction\', SET Description = \'The lives of two mob hitmen, a bo\' at line 1',
sqlState: '42000',
index: 0,
sql:
'UPDATE moviesList SET Rank = 5, SET Title = \'Pulp Fiction\',
SET Description = \'The lives of two mob hitmen, a boxer, a gangster\\\'s wife, and a pair of diner
bandits intertwine in four tales of violence and redemption.\',
SET Runtime = 154, SET Genre = \'Crime, Comedy\', SET Rating = 8.9, SET Metascore = 94, SET Votes = 1511653, SET Gross_Earning_in_Mil = 107.93, SET Director = \'Quentin Tarantino\', SET Actor = \'John Travolta\', SET Year = 1994 WHERE Id = 5' }
The issue is w.r.t the fields defined .
You should define in an following format
For Example:
let fields = 'SET Rank =? , Title =?, Description =? , Runtime =?, Genre =?, Rating =? '
Please refer this link:
https://www.technicalkeeda.com/nodejs-tutorials/nodejs-mysql-update-query-example
The module provides a lot of flexibility that can save you time if you build each step of the process thoughtfully. It will accept an object for an INSERT or UPDATE as long as the keys match the column names of corresponding fields in the table you're querying.
So, if you have the ability to define the key values coming in via req.body you can let things flow through very easily without any additional manipulation or mapping.
Consider the following updated example of your code with a sample of how you would need to structure req.body upstream:
// example of what req.body would need to look like:
{
"Rank": "value_a",
"Title": "value_b",
"Description": "value_c",
"Runtime": "value_d",
"Genre": "value_e",
"Rating": "value_f",
"Metascore": "value_g",
"Votes": "value_h",
"Gross_Earning_in_Mil": "value_i",
"Director": "value_j",
"Actor": "value_k",
"Year": "value_l"
}
app.put("/api/movies/:id", (req, res) => {
let id = req.params.id;
let payload = req.body;
connection.query("UPDATE moviesList SET ? WHERE Id = ?", [payload, id], (err, rows) => {
if (err) throw err;
console.log('changed ' + rows.changedRows + ' rows');
// res.send(rows.message);
// in this context rows is the response object from the module
// message is not a sub-object of the feature so rows.message
// would likely fail
});
})

Get all items from the parent table, but switch out the foreign key with a column from the child table

I have two tables in mysql and I'm trying to make a query call. In the Item table, the tid is a foreign key, but in the query call, I want to get all the information in the Items table, but instead of getting the tid, I want to get the name of the Types the tid refers to. What is the proper query call here?
|_______Items______| |________Types______|
| id {PK} | | tid {PK} |
| name | | name |
| description | | description |
| tid {fk} | | |
app.get('/getData', function(req, res) {
var content = {};
mysql.pool.query('SELECT * FROM Items WHERE id=?', [req.query.id],
function(err, rows, fields) {
if (err) {
next(err);
return;
}
content.results = JSON.stringify(rows);
res.send(content.results);
});
});
I believe the correct query should be:
mysql.pool.query('SELECT * FROM Items INNER JOIN Types on Types.tid = Items.tid WHERE Items.id=?', [req.query.id],
This will return all the fields from both tables, but only show the row from Types where the tid is used in the row of Items which has the id passed in req.query.id
This is done using a SQL INNER JOIN - if you're not familiar with this way of joining tables, it's quite fundamental to SQL and you should study it.
P.S. If you want just a specific selection of columns from the two tables (as hinted at in the question), you can write it like this, for instance:
mysql.pool.query('SELECT Items.id, Items.name, Items.description, Types.name FROM Items INNER JOIN Types on Types.tid = Items.tid WHERE Items.id=?', [req.query.id],

Inserting Array values from jQuery into PHP

I am using PHP, MySql, jQuery.
I have a html table. I want to get the contents of the html table, and store it in mysql db.
I have taken the contents of the html table in an array using jquery.
This is my jquery code.
var myTableArray = [];
$("#my_tbe tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
So 'myTableArray' will gives me the id, name, code.
1,sam,z123
2,kim,z234
Here is my MySql Table.
---------------------
id | name | code
---------------------
3 | sample1 | kkk
4 | sample2 | iii
---------------------
i am getting values in jquery through .text(). How do i insert these values into my DB.
Thanks.
First of all, you need to send request via Aajx.
var request = $.ajax({
url: "insert.php", // Action file
type: "POST", // POST method
data: { data : myTableArray }, // Your data
});
In insert.php you will get something like this:
$_POST["data"] = array(
array(1, "sam", "z123"),
array(2, "kim", "z234")
);
Mysql insert sytnax looks like:
INSERT INTO table (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
You need to loop through your data and fill your data into syntax above.
$values = array();
foreach($_POST["data"] as $insert){
$values[] = "({$insert[0]}, '{$insert[1]}', '{$insert[2]}')";
}
{$insert[0]} is missing quotes, beacue is integer. You can use NULL instead if is autoincrement.
Your values are ready, now put them into query:
$query = "INSERT INTO table (id, name, code) VALUES".implode(',', $values).";";
You are ready to execute query string!
I preffer use prepared statements like following solution:
$values = array();
$data = array();
foreach($_POST["data"] as $insert){
$values[] = "(?, ?, ?)";
$data = array_merge($data, $insert);
}
Now $data contains all your data.

Insert Value in Mysql via node.js

I use Node.js and i want to INSERT few value in my table.
like:
id | profile_id | user_id
1 | 2 | 7
2 | 2 | 3
3 | 2 | 4
4 | 2 | 6
i have an array (user_id) with all my date(ids), i have to do a foreach in my array for insert each user_id value like
foreach...
connection.query('INSERT INTO mytable SET ?', my_obj, function(error,risultato) { ...
or i can do a cycle inside mysql with one statement?
You can use the following syntax for multiple insterts in MySQL:
INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?);
Therefore yor code would be:
connection.query("INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?)",
[id1, profile_id1, user_id1, id2, profile_id2, user_id2, id3, profile_id3, user_id3],
function(err, result){ .... });
After answer #Mustafa i do it: (use sugar.js and felixge/node-mysql)
var place ="(";
rows.each(function(n) {
columns.add(n.profile_id);
columns.add(n.user_id);
columns.add(new Date());
place += '(?,?,?),';
});
place= place.slice(0,place.lastIndexOf(","));
var sql = 'INSERT INTO mytable (profile_id,user_id,created) VALUES '+place+' ON DUPLICATE KEY UPDATE id=id';
connection.query(sql,
columns
, function(error, rows) {
if (error) {
var err = "Error on " + error;
console.dir(err);
console.log('>>>>>ERROR<<<<< ' + err);
throw err;
}
connection.release();
callback(rows);
I hope to help someone

Categories