I have a table with different post categories and I want to get the categories ID from the name. Example name: random => id: 1.
I got the variable like this:
const { name, title, cat, con, user_file } = req.body;
console.log(cat); //returnes the name as it should
This is my query:
var sql = "SELECT id FROM cat WHERE cat_name = ?";
db.query(sql, cat, function(err, result) {
if(!result){
return next();
}
const cat_id = result[0];
});
If I than try to console.log the cat_id I get undefined. I have tried doing this in many different way but it comes out the same every time. If I just run
SELECT id FROM cat WHERE cat_name = random
in thee database manager it works like it should and returnes the ID.
Edit: The purpose is to get the id to insert a foreign key into another table.
Your results is an empty array. This is (assuming you're using the mysql package) because your function call is incorrect.
When passing arguments to your query, as explained here, you need to pass an array of values, not just a single value. For example:
connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
In your case, that means you're looking for cats where the name is the first character of cat (e.g. cat[0]).
It ended up being a problem with variables only being saved in the query level. It console.logged the right number inside the db.query and the wrong one out of the db.query. So the solution for now is to put it inside I guess.
My solution now looks like this:
exports.post = (req, res, next) => {
let { cat } = req.body;
let cat_id = 0;
db.query(
"SELECT id FROM cat WHERE cat_name = ?",
[cat],
async function (err, results) {
if (!err) cat_id = results[0].id;
else console.log(err);
db.query(
"INSERT INTO posts SET ?",
{ cat_id: cat_id },
(error, results) => {
if (error) console.log(error);
else res.status(200).redirect("/post");
}
);
}
);
};
Related
I'm writing a simple online videogame with node js and I want to manage the score of each player saving it in a database(mysql).
Now in the server side I have a piece of code like this:
socket.on('game_over',function(data){
for (var i = 0; i < players.length; i++) {
if(players[i].id == data.id){
var sql;
sql='UPDATE login SET email=? WHERE username=?'
connection.query(sql, [data.score,"d"],function(error, results, fields) {
console.log(sql);
console.log(error);
if (error) throw error;
console.log(result);
});
players.splice(i,1);
break;
}
}
socket.broadcast.emit('p_disconnect',data.id);
});
When I start my server and a game_over signal is recived, my server disconnect.
The print of the sql query is correct and I don't see any error since it return me 'null'
Why my server disconnect after that, and more importantly what can I do to keep the server up?
Without the connection.query part it works like it should
Based on the comment on the question:
// assuming
const players = [
{id: 1, otherInfo: 'foobar' },
{id: 2, otherInfo: 'foobar' },
]
const connection = mysql.connect() // something like this
// When the game ends we assume that the game_over event is fired
socket.on('game_over',function (data) {
// "I need to find the correct player"
const correctPlayer = players.find(player => player.id === data.id)
// "and delete it from the list of the active players"
const position = players.indexOf(correctPlayer)
players.splice(position, 1)
// "and update the database with it's score" => depends on your DB structure
const query = `UPDATE youTable SET score = ${data.score} WHERE playerId = ${correctPlayer.id}`
// here depends on how you want to manage the query result (some examples)
// run query (is async cause how js works) and just log the result
connection.query(sql, function(error, results, fields) {
// this code is executed when the query ends
console.log(error, results, fields)
}
// this code is executed after starting the query
socket.broadcast.emit('p_disconnect', data.id);
// run query and emit event after the query ends
connection.query(sql, function(error, results, fields) {
socket.broadcast.emit('p_disconnect', data.id);
console.log(error, results, fields)
}
});
I am writing code in conjunction with sql on node js.
I want to load the data according to the condition, and I want to dynamically get the condition depending on the variable.
Here is the current code:
db.all ("select CollectionID, CollectionName from Collection where
CollectionID = abc", function () {
How do I want to receive data according to the variable abc ?
abc's value is number .
var abc = 1;
var query = 'select CollectionID, CollectionName from Collection where CollectionID = ?'
db.all (query, [abc], function (err, rows) {
if (err) throw err;
console.log(rows);
});
I'm having trouble executing my update query. Right now it's inside the select query witch works fine, the update queries are well formed, since I can copy paste a single update query from the output and it will update accordingly. no errors thrown, stream with update string appear but none are executed.
connection.connect();
connection.query('SELECT text, id from twits2 order by id ASC', function(err, rows) {
rows.forEach(function(row){
var id = row.id;
var r1 = sentiment(row.text);
var score = r1.score;
var comparative = r1.comparative;
var q = 'UPDATE twits2 SET score ="'+score+'", comparative ="'+comparative+'" WHERE id="'+id+'"';
console.log(q);
connection.query(q, function (error, results, fields) {
if (error) throw error;
});
});
How to insert two table in one time?
I need to insert second table user_information the field user_id with first table user insert returning id, I found this answer but I can't find how to be with params prepared statements
var dbQuery = 'WITH insertUser AS (
INSERT INTO "user" (status, create_date) VALUES ($1, $2) RETURNING id
)
, insertUserInformation AS (
INSERT INTO user_information (user_id, email) VALUES ($3, $4)
)
';
yield queryPromise(dbClient, dbQuery, [status, timestamp, ??, email]);
pg
Use transactions. That way either all queries will be committed, or none will be committed. And the incomplete state before you have executed all queries is not visible for other processes.
More on how to do transactions in node-postgres is available at https://github.com/brianc/node-postgres/wiki/Transactions
And for reference the most relevant section is:
var Client = require('pg').Client;
var client = new Client(/*your connection info goes here*/);
client.connect();
var rollback = function(client) {
//terminating a client connection will
//automatically rollback any uncommitted transactions
//so while it's not technically mandatory to call
//ROLLBACK it is cleaner and more correct
client.query('ROLLBACK', function() {
client.end();
});
};
client.query('BEGIN', function(err, result) {
if(err) return rollback(client);
client.query('INSERT INTO account(money) VALUES(100) WHERE id = $1', [1], function(err, result) {
if(err) return rollback(client);
client.query('INSERT INTO account(money) VALUES(-100) WHERE id = $1', [2], function(err, result) {
if(err) return rollback(client);
//disconnect after successful commit
client.query('COMMIT', client.end.bind(client));
});
});
});
It's impossible in postgresql. I solved exact the same problem by creating function and simply executing with parameters. As I see in your table structure, you don't have many attributes, so this will be relatively easy.
Example code:
function.sql
CREATE OR REPLACE FUNCTION createSomething
(
IN attr1 VARCHAR(20),
IN attr2 VARCHAR(200)
)
RETURNS void AS $$
DECLARE userId INTEGER;
BEGIN
INSERT INTO table1 (col1, col2) VALUES
(
attr1,
attr2
) RETURNING id INTO userId;
INSERT INTO table2 (user_id, col11, col2) VALUES
(
userId,
col11,
col12
);
END;
$$ LANGUAGE plpgsql;
Usage:
SELECT createSomething('value1', 'value2');
Please notice, that second insert statement will know what was recently user's id and will use it.
PostgreSQL Prepared Statements will not let you do it. You will have to use a transaction.
Below is your example implemented with pg-promise, using ES7 syntax:
const pgp = require('pg-promise')({
// initialization options;
});
const db = pgp(/* your connection object or string */);
db.tx(async t => {
const user = await t.one('INSERT INTO user(status, create_date) VALUES($1, $2) RETURNING id', [status, timestamp]);
return t.none('INSERT INTO user_information(user_id, email) VALUES($1, $2)', [user.id, email]);
})
.then(() => {
// SUCCESS;
})
.catch(error => {
// ERROR;
});
I do not believe this can be accomplished as a natural sql statement. You have to wrap it up as a procedure or some other mechanism.
I am weighting a node.js application, the result I get from my mysql query is,
[ RowDataPacket { name: 'ubuntu' } ]
(Ubuntu is the only thing in the row)
What I would like to do is shorten my variable, "results" so that it equals ubuntu for example, or just every thing between the '', I am new to JS. I am using the standard way of querying the sql database,
It is being done as so:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root', //just using root for my personal testing.
password : 'root',
database : 'Sonic'
});
connection.connect();
var connect = connection.query( 'SELECT name FROM Sonic_url',
function(err, fields, results, rows) {
// if (results === input) {
var sqldata = results.substring(1, 4);
console.log(results);
if (err) throw err;
// console.log('I belive we have found what you are after, is: ' + input + ' ' + 'what you are after?');
//}
});
I would like to be able to do a basic IF with the variable input and a variable from the mysql query, so I can print to screen if the result was found or not.
The correct signature for the mysql query is:
connection.query(query, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
What you want is to log the value of name. If your query produces one result, you can access this value from the first item in the rows array:
connection.query('SELECT name FROM Sonic_url', function(err, rows, fields) {
console.log(rows[0].name);
});