How to insert a data into a MySQL database via a variable? - javascript

I am trying to insert values defined in javascript at the start of the program. But it does not like me trying to insert variables, instead, I should enter the raw name.
This is the error code:
Error: ER_BAD_FIELD_ERROR: Unknown column 'username' in 'field list'
I am using a SQL database and javascript to interact with it. The value has been defined with a variable beforehand.
var username = "Mark Graham"
var password = 13.00
con.connect(function(err) {
var username = "Mark Graham"
var password = 13.00
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO staff (name, hours) VALUES (username, password)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
It should insert Mark Graham into the database.

Implements a ORM, Sequelize or use
connection.query('INSERT INTO staff (name, hours) VALUES (?, ?)', [YourVar,YourSecondVar], 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)
});
or
connection.query({
sql: 'INSERT INTO staff (name, hours) VALUES (?, ?)',
timeout: 40000, // 40s
values: [varOne,varTwo]
}, 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)
});

Related

Express JS TypeError: Cannot read properties of undefined (reading '0') SQL query error

I am trying to Insert something in my db and then access to it directly after, but because node is async, this somehow does not work as planed. But I know that there must be a way to get this going.
Heres my code:
router.post('/anzeigeerstellen', upload_inserat.single('Anzeigebild'), function (req, res) {
let titel = req.body.TitelderAnzeige,
beschreibung = req.body.Beschreibung,
inbild = req.file.filename,
ses = req.session;
pool.query("INSERT INTO inserat (titel, beschreibung, inseratbildname, email)
VALUES (?, ?, ?, ?)",
[titel, beschreibung, inbild, ses.email],
(error, results, fields) => {
pool.query("SELECT iid FROM inserat WHERE titel = ?, beschreibung = ?,
inseratbildname = ?, email = ?",
[titel, beschreibung, inbild, ses.email],
(error, results, fields) => {
res.redirect('anzeige?id=' + results[0].iid);
});
});
});
And the error is the following:
TypeError: Cannot read properties of undefined (reading '0')
I've tried async and await but it didn't work for me (and I'm also not sure if I used it right, to be honest).
Every SQL query is a promise which means when you insert or ask the database to get (select) data for you it takes some time for the server to execute your query. Since NodeJs has synchronous nature, it goes to execute the next line of the code before you get the result from the database. Therefore, you got undefined.
I didn't quite understand the purpose of the select statement but if you wanted to know the id of the inserted row, the SQL returns it for you as a result.
So, if you wish to you javascript asynchronously, the query would look like this:
//Setting the route asynchronous
router.post('/anzeigeerstellen', upload_inserat.single('Anzeigebild'), async (req, res)=> {
let titel = req.body.TitelderAnzeige,
beschreibung = req.body.Beschreibung,
inbild = req.file.filename,
ses = req.session;
//Awaiting until the db resolves
await pool.query("INSERT INTO inserat (titel, beschreibung, inseratbildname, email)
VALUES (?, ?, ?, ?)", [titel, beschreibung, inbild, ses.email],
(err, results, fields) => {
//Always check if there is an error
if (err) console.error(err)
else console.log(results) //results should be the id of the row or the row itself
/*pool.query("SELECT iid FROM inserat WHERE titel = ?, beschreibung = ?,
inseratbildname = ?, email = ?",
[titel, beschreibung, inbild, ses.email],
(error, results, fields) => { There is no need for this query since the results of the upper query is the row you wanted*/
res.redirect('anzeige?id=' + results[0].iid);
//});
});
});

How to return ID when new entry is recorded with a trigger express js and MYSQL

I am currently using express and workbench to configure a database where I can create, view and update cars.
Right now when I POST a new car it creates a new entry with the inputs manufacturer, model and price, and I use a trigger which I used inside workbench to configure a UUID for each vehicle. However, I want to be able to return this new UUID when a new record is created in my app.post function.
Here is my post function:
//Allow post methods
app.post('/cars', (req, res) => {
if (req.query.manufacturer && req.query.model && req.query.price) {
console.log('Request received'); //logging to check if post request has beeen made
connection.connect(function(err) { //query the connection then call an SQL INSERT method to put new record in database.
connection.query(`INSERT INTO main.cars (manufacturer, model, price) VALUES ('${req.query.manufacturer}', '${req.query.model}', '${req.query.price}')`, function(err, result, fields) {
if (err) res.send(err);
if (result) res.send({manufacturer: req.query.manufacturer, model: req.query.model, price: req.query.price}); //sending the fields to the response (res)
if (fields) console.log(fields);
console.log(result)
});
});
} else {
console.log('Missing a parameter');
}
});
Right now it just returns the new fields inputted in postman but not the new uuid (id) and am quite unsure how to do this, as it is created in a trigger in workbench:
CREATE DEFINER=`admin`#`%` TRIGGER `cars_BEFORE_INSERT`
BEFORE INSERT ON `cars` FOR EACH ROW BEGIN
SET new.id = uuid();
END
Query the table to get the id that was assigned to the manufacturer/model that was just inserted.
Also, use a database query with parameters rather than substituting request parameters directly into the SQL, to protect against SQL injection.
connection.connect(function(err) { //query the connection then call an SQL INSERT method to put new record in database.
connection.query('INSERT INTO main.cars (manufacturer, model, price) VALUES (?, ?, ?)', [req.query.manufacturer, req.query.model, req.query.price], function(err, result, fields) {
if (err) {
res.send(err);
} else {
connection.query('SELECT id FROM main.cars WHERE manufacturer = ? AND model = ?', [req.query.manufacturer, req.query.model], function(err, result) {
if (err) {
res.send(err);
} else {
res.send({
manufacturer: req.query.manufacturer,
model: req.query.model,
price: req.query.price,
id: result[0].id
});
}
});
}
});
});

NodeJs insert current Datetime field into MySQL db

I'm trying to insert a DATETIME field into my MySQL db.
var dt = require('moment')().format('YYYY-MM-DD HH:mm:ss');
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id],
[dt],
(error, results, fields) => {
}
);
I get this error:
C:\Users\tiger\Desktop\prova\REST_API_WITH_MYSQL-master\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^TypeError: this._callback.apply is not a function
If I try this code, everything comes right:
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,"2021-01-27 00:00:00")`,
[results[0].id],
//[dt],
(error, results, fields) => {
}
);
What i'm doing wrong?
You have your parameters in 2 separate arrays. Put your parameters in the same parameter array.
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id, dt],
(error, results, fields) => {
}
);
The correct format probably is YYYY-MM-DD HH:MM:SS(I think it depends on MySQL configuration, but this is the default) as the docs points out.
So you should try using moment's format() method like this:
const myDate = moment(data.myTime.format('YYYY/MM/DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id, myDate],
(error, results, fields) => {
}
);

mySql Insert Syntax - Not Inserting What's Expected

I have this INSERT query. It does create a record in the table, but "client" value is 0, and "short" value is null. However, all of the console logs show the correct data. I'm assuming this is a simple syntax error in my use of the question marks. But I can't find that, or seem to get it to work using just variable names either. Any help is appreciated.
app.put("/audit/create", function (req, res) {
console.log("It is getting to the route");
const client = req.body.client;
const short = req.body.short;
console.log(`client: ${client}`);
console.log(`short: ${short}`);
connection.getConnection(function (err, connection) {
connection.query(
`INSERT INTO audits (client, short)
VALUES (?, ?)`,
[
{
client: client,
},
{
short: short,
},
],
function (error, results, fields) {
if (error) throw error;
res.json(results);
console.log(`Audit has been created`);
}
);
connection.release();
});
});
I've also tried using the variables names of ${client}, ${short} in place of the questions marks... and that still gives me the same result. However the console logs that render ${client} and ${short} do log the correct data I'm expecting to see.
Why are you passing objects as the values to the query? Try just:
connection.query(
'INSERT INTO audits (client, short) VALUES (?, ?)',
[ client, short ],
function ...

Error: ER_BAD_FIELD_ERROR: Unknown column 'organizations.leader' in 'where clause' [duplicate]

This question already has answers here:
mysql update column with value from another table
(9 answers)
Closed 2 years ago.
I made this code where after I type a command it updates a database. In the last query, the database thinks there's no column named leader in the organizations table, but there is (the query above uses it). What's wrong?
I'm using MySQL Workbench 8.0.
mp.events.addCommand("organizations", (player, _, abb, namee, hqID) => {
const socialID = player.rgscId;
con.query("SELECT orgID FROM players WHERE scID = "+socialID+"", function (err, result) {
resultado = result[0].orgID
if (!abb) {
// not relevant
}
else {
con.query("SELECT playerID FROM players WHERE scID = "+socialID+"", function (err, result) {
leaderID = result[0].playerID
con.query("INSERT INTO organizations (abb, namee, leader, hqID) VALUES (?, ?, ?, ?)", [abb, namee, leaderID, hqID], function (err, result) {
if (err) {
//not relevant
}
});
con.query("UPDATE players SET player.orgID = organizations.orgID WHERE players.playerID = organizations.leader", function (err, result) {
if (err) console.log(err)
});
});
}
});
});
UPDATE players, organizations
SET player.orgID = organizations.orgID
WHERE players.playerID = organizations.leader

Categories

Resources