var prefix = `SELECT S_PREFIX FROM ServerConfigs WHERE S_ID = ${message.guild.id}`;
connection.query(prefix, function (err, result, fields) {
if (err) return console.log(err);
let res = JSON.parse(JSON.stringify(result[0].S_PREFIX));
const serverPREFIX = res;
It works but sometimes it writes me an error to console.
The error looks like this:
TypeError: Cannot read property 'S_PREFIX' of undefined
Could anybody help me please? Just started learning MYSQL.
result[0] is undefined, which means that your SQL query returned no results, meaning that there were no rows with the S_ID being message.guild.id. Just check that the result array is not empty.
var prefix = `SELECT S_PREFIX FROM ServerConfigs WHERE S_ID = ${message.guild.id}`;
connection.query(prefix, function (err, result, fields) {
if (err) return console.log(err);
if (result.length < 1) {
console.log(`No results for S_ID = ${message.guild.id}`)
return;
}
let res = JSON.parse(JSON.stringify(result[0].S_PREFIX));
const serverPREFIX = res;
Related
I'm having some trouble with below code. Can someone please take a look and advise what's going on?
const name = ["a", "b", "c"]
let query1 = ('SELECT name FROM table WHERE name = ? AND status IN ("Pending","Active") limit 1')
if (name instanceof Array) {
async function getNames() {
try {
name.forEach(async (name) => {
let newName = []
let rows = await promisePool.query(query1, name);
if (rows[0].length > 0) {
if (rows[0])
newName.push(rows[0][0].uid_name)
console.log(newName)
}
return (rows);
})
}
catch (err) {
console.log('ERROR => ' + err);
return err;
}
}
await getNames();
console.log(newName) returns (if row is found)
['a']
['b']
how can I push any returning value to the array ? desired output ['a','b'] so I can compare it to the original array.
Thanks in advance,
Ucin
I have changed the code a bit but to be honest I'm still not that of an expert.
const name = ["a","b","c"]
let query1 = ('SELECT name FROM table WHERE name = ? AND status IN ("Pending","Active") limit 1')
if (name instanceof Array) {
async function getNames() {
try {
for(names of name) {
let rows = await promisePool.query(query1,[uid,challenge_type,names]);
return (rows);
}
}
catch (err) {
console.log('ERROR => ' + err);
return err;
}
}
let newVar = await getNames();
console.log(newVar[0])
the newVar only returns 1 line, where there should be 2 names.
name.forEach(async (element) => {
let rows = await promisePool.query(query1,[uid,challenge_type,element]);
if (rows[0].length > 0) {
if (rows[0])
/* newName.push(rows[0][0].uid_name) */
console.log(rows[0])
return (rows);
if I go with forEach...Of, I can console.log it within scope, but return(rows) is undefined
Is there a specific reason you are looping through the names and executing a query per name? If all you want to do is see which of those names in the array already exist in your database you could do it all in a single query. Something like:
const names = ["a","b","c"];
const query = 'SELECT name FROM table WHERE name IN (?) AND status IN ("Pending","Active")';
const result = await promisePool.query(query, [names]);
console.log(result);
So, I have this code. I'm trying to debug it in forever. I dont know why it is returning error. I might have some element of promise I forgot or I have something wrong with my array.push 'cause when I look at the log, it throws error on line where I push some objects into array.
Here is my code so far:
router.post('/inventory/product/stocks/add/(:id)', authenticationMiddleware(), function(req, res, next) {
const db = require('../db.js')
var product_no = req.params.id
var cog = req.body.cog
var size_slug = req.body.size_slug
var size_name = req.body.size_name
var rowinserted = 0
var initial_stock = req.body.initial_stock
var stock_id = new Array
var batch_id = new Array
var stock = new Array
var batch = new Array
new Promise(function(resolve, reject) {
console.log('one');
// Getting product product_slug for product_sku
let sql = `SELECT product_slug
FROM inventory_tbl
WHERE product_no = ?`
db.query(sql, [req.params.id], (error, results, fields) => {
if (error) {
throw error;
} else {
var product_slug = results[0].product_slug
resolve(product_slug)
}
})
})
.then(function(value) {
console.log('two');
// Insert product sizes together with its initial stock
for (var x = 0; x < size_slug.length; x++) {
var product_sku = value + size_slug[x]
var slug = size_slug[x]
var name = size_name[x]
var initial_stock = initial_stock[x]
console.log(product_sku);
if (size_slug[x] != '') {
stock.push({
product_sku: product_sku,
product_no: product_no,
size_slug: slug,
size_name: name,
total_stock: initial_stock,
available_stock: initial_stock
})
}
console.log(stock);
}
for (var x = 0; x < size_slug.length; x++) {
var product_sku = value + size_slug[x]
var initial_stock = initial_stock[x]
if (size_slug[x] != '') {
batch.push({
product_no: product_no,
product_sku: product_sku,
production_date: mysql.raw('CURRENT_TIMESTAMP'),
batch_cog: cog,
initial_stock: initial_stock,
stock_left: initial_stock
})
}
console.log(batch);
}
return value
})
.then(function(value) {
console.log('three');
// Insert rows to product_tbl and stock_tbl
for (var i = 0; i < stock.length; i++) {
let sql = `INSERT INTO product_tbl(product_sku, product_no, size_slug, size_name, total_stock, available_stock) VALUES (?, ?, ?, ?, ?, ?)`
db.query(sql, [stock[i].product_sku, req.params.id, stock[i].size_slug, stock[i].size_name, stock[i].total_stock, stock[i].available_stock], (error, results, fields) => {
if (error) throw error
db.query(`SELECT LAST_INSERT_ID() AS id;`, (error, results, fields) => {
stock_id[i] = results[0].id
})
})
sql = `INSERT INTO stocks_tbl(product_no, product_sku, production_date, batch_cog, initial_stock, stock_left) VALUES (?, ?, CURRENT_DATE, ?, ?, ?)`
db.query(sql, [req.params.id, batch[i].product_sku, batch[i].batch_cog, batch[i].initial_stock, batch[i].stock_left], (error, results, fields) => {
if (error) throw error
db.query(`SELECT LAST_INSERT_ID() AS id;`, (error, results, fields) => {
batch_id[i] = results[0].id
})
})
rowsupdated++
}
return value
})
.then(function(value) {
console.log('four');
// Render the web page
if (rowinserted != sizeslug.length) {
req.flash('error', error)
res.redirect('/admin/inventory/product/stock/add/' + req.params.id)
} else {
req.flash('success', 'Data added successfully!')
res.redirect('/admin/inventory/product/stock/add/' + req.params.id)
}
})
.catch(function(error) {
console.log('error');
// Error handler
for (var i = 0; i < rowinserted; i++) {
let sql = `DELETE FROM product_tbl WHERE product_sku = ?`
db.query(sql, [stock_id[i]], (error, results, fields) => {
if (error) throw error
})
sql = `DELETE FROM stocks_tbl WHERE product_sku = ?`
db.query(sql, [batch_id[i]], (error, results, fields) => {
if (error) throw error
})
}
res.redirect('/admin/inventory/product/stock/add/' + req.params.id)
})
})
My log returns:
one
two
error
Edit: The process stops (I'm not sure the specific line but according to the log output) after console.log('two') because I tried putting some log as well after the for loops but they don't proceed there. It just go to the .catch/error.
Instead of outputting a string in console.log('error'); dump out an actual error object that you receive in the catch handler. It will give additional details of why and where it fails. I suspect that the code after console.log('two'); throws an exception and then you unintentionally swallow it below.
Consider splitting your code into separate thematic functions. That way you will be able to maintain and spot the errors (or typos) much easier.
Looking at the output, i can see that console.log(product_sku); this is not getting printed. So, actually the problem is var initial_stock = initial_stock[x]. You have declared the local variable(to your then callback function) with same name as global variable(to your route.post callback functions) and now your global initial_stock variable is masked with local one, which is not an array (actually is undefined). So try changing the variable name to something else in your then block and see if problem disappear.
Hope this helps.
I have written a function and exported it using exports. Inside the function I have 2 nested queries. When I have only 1 query I am able to view the values of result. But, after adding the outer query the value of the result from the outer query is undefined.
Here is the code:
main.js
var new1 = function () {
connection.query("select ID from tbl1", function (error, result, fields) {
console.log(result) // This is displayed as undefined.
for (var id in result) {
connection.query("select name from tbl2 where ID = '" + result[id].ID + "' ", function (err, result, fields) {
if (err) throw err
for (var count in result) {
console.log(result[count].name)
}
})
}
})
}
export.new1 = new1;
and in the app.js:
var new2 = require('./main');
new2.new1();
Thank you.
I was going to edit and fix your indentation, but then I saw you are missing a closing quote for the string on the second line: "select ID from tbl1
Now someone else have edited your code and added a closing quote
I want to add + 1 to the database and with that I would have 2 in the database if I had 1 in the case, I tried it but got 11, not 2
if (result4.length) {
var sql1 = `UPDATE level SET xp = '${result4[0].xp + 1}' WHERE xp = '${result4[0].xp}'`;
connection.query(sql1, function(err, result) {
if (err) throw err;
});
}
Here is the full source, just in case:
client.on("message", message => {
if (message.author.bot) return;
connection.query(`SELECT * FROM guildn WHERE id = '${message.guild.id}'`, function(err, result3) {
if (err) {
return console.log('Error1');
}
if (result3.length) {
connection.query(`SELECT * FROM level WHERE id = '${message.author.id}'`, function(err, result4) {
if (err) {
return console.log('Error1');
}
if (!result4.length) {
var sql = `INSERT INTO level (guild , id , nivel , xp) VALUES ('${message.guild.id}','${message.author.id}','0','1')`;
connection.query(sql, function(err, result) {
if (err) throw err;
console.log("1 record inserted");
return
});
}
if (result4.length) {
var sql1 = `UPDATE level SET xp = '${result4[0].xp + 1}' WHERE xp = '${result4[0].xp}'`;
connection.query(sql1, function(err, result) {
if (err) throw err;
});
}
});
}
});
});
I used the google translator to make this post, so if I have any errors in the translation, I'm sorry
My suspicion would be that the result from the database xp is a string. This seems logical since you are setting it as a string in your query. In that case you would do this:
`UPDATE level SET xp = '${parseInt(result4[0].xp) + 1}' WHERE xp = '${result4[0].xp}'`;
This converts the result to a number and javascript will add 1 to it, rather than concatenating 1 to the string.
I'm guessing what's happening is that your XP data is stored in your database as a string so you end up trying to add a number to a string. In Javascript, the result in that situation is that you concatenate the number to the end of the string, which is why you end up with '11' instead of 2.
To resolve the issue without changing the database, you can turn the XP string into an integer using parseInt before adding 1 to it:
var sql1 = `UPDATE level SET xp = '${ parseInt (result4[0].xp) + 1}' WHERE xp = '${result4[0].xp}'`;
If the data type of xp is a string then a little modification to your update call would suffice:
if (result4.length) {
const query = `UPDATE level SET xp = '${Number(result4[0].xp) + 1}' WHERE xp = '${result4[0].xp}'`;
connection.query(query, function(err, result) {
if (err) throw err;
});
}
Select statements are working fine, but whenever I try an insert or update the recordset and affected values are undefined. The insert/update works in the DB, I just can't read the returned values.
var sql = require('mssql');
var config = {...};
sql.connect(config).then(function() {
new sql.Request().query("INSERT INTO MyTable (Name, Age) VALUES ('John', 30)").then(function(recordset, affected) {
console.log('Recordset: ' + recordset);
console.log('Affected: ' + affected);
}).catch(function(err) {
console.log('Request error: ' + err);
});
}).catch(function(err) {
if (err) {
console.log('SQL Connection Error: ' + err);
}
});
The output to console is:
Recordset: undefined
Affected: undefined
I feel like I must be missing something really simple here.
As mentioned in the comments, INSERT statement doesn't return a recordset so recordset is undefined. Please see this section of the docs to learn more about how to get number of affected rows.
The problem with your code is you're expecting affected as a second argument from the promise, but promises does only support one argument. Because of that you must access number of affected rows this way:
var sql = require('mssql');
var config = {...};
sql.connect(config).then(function() {
var request = new sql.Request();
request.query("INSERT INTO MyTable (Name, Age) VALUES ('John', 30)").then(function(recordset) {
console.log('Recordset: ' + recordset);
console.log('Affected: ' + request.rowsAffected);
}).catch(function(err) {
console.log('Request error: ' + err);
});
}).catch(function(err) {
if (err) {
console.log('SQL Connection Error: ' + err);
}
});
If you want id to be output parameter
const sql = require("mssql/msnodesqlv8");
const pool = new sql.ConnectionPool(dbConfig);`
const poolConnect = pool.connect();
let query = `INSERT INTO <table>(fields) VALUES(values);SELECT #id = SCOPE_IDENTITY()`
await poolConnect;
pool.request()
.output("id", sql.Int)
.query(query).then((err, result) => {
console.log(result.output.id)
}).catch(err => {
console.log(err)
})`