I'm having difficulty comprehending the implementation of prepared statements. I've done a fair amount of research but most of the information I found is either out of context or contain examples far more complex than what I'm trying to accomplish. Can anyone clarify for me why the execute method in the second example below is throwing a syntax error?
NOTE: I'm using the node-mysql2 package here.
controller.js (using query mysql method)
const db = require("../lib/database");
async addNewThing(req, res, next) {
let data = req.body
const queryString = 'INSERT INTO table SET ?'
try {
await db.query(queryString, data)
res.status(201).json({
message: 'Record inserted',
data
})
} catch (error) {
next(error)
}
}
Record is successfully inserted into the database
controller.js (using execute mysql method)
const db = require("../lib/database");
async addNewThing(req, res, next) {
let data = req.body
const queryString = 'INSERT INTO table SET ?'
try {
await db.execute(queryString, [data])
res.status(201).json({
message: 'Record inserted',
data
})
} catch (error) {
next(error)
}
}
Results in the following error:
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 '?' at line 1
data
{ thing_id: '987654', thing_name: 'thing' }
With .query(), parameter substitution is handled on the client, including objects which let data = req.body is in the above examples.
With .execute() prepared statement parameters are sent from the client as a serialized string and handled by the server. Since let data = req.body is an object, that's not going to work.
Related
I am using MySQL placeholders and create promise to use them with async await.
selectTickets: (variable) => {
const sqlStatement = `SELECT * FROM tickets WHERE userID = ?`;
return new Promise((resolve, reject) => {
db.query(sqlStatement, variable, (error, response) => {
if (error) return reject(error);
return resolve(response);
});
});
},
i tried even to create the statement with interpolation and gave me an error:
"Unknown column 'undefined' in 'where clause'"
This is my code. But when I am using it in react, I am getting Error 500 status saying that the statement is incorrect.
ode: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1",
sqlState: '42000',
index: 0,
sql: 'SELECT * FROM tickets WHERE userID = ?'
I tried alot of other methods. But other functions that uses same type of function with same type of statement are working just fine.
In react I have this call:
const URL_TICKETS_BY_USERID = 'http://localhost:3000/api/get-tickets';
const config = {
headers: { Authorization: `Bearer ${user.token}` }
};
const userID = user.userID;
axios.get(URL_TICKETS_BY_USERID,
userID,
config
)
.then(data => console.log(data))
.catch(error => console.log(error))
Can i have some help?
The problem lies with your db.query() call. The second parameter should be an array, even for single values. This should work:
db.query(sqlStatement, [variable], (error, response) => {
if (error) return reject(error);
return resolve(response);
});
Also axios get() takes two parameters: url and config (optional). This means that any params should be part of that config object:
const config = {
headers: { Authorization: `Bearer ${user.token}` },
params: {
id: user.userID
}
};
axios.get(URL_TICKETS_BY_USERID, config)
Alternatively pass it as a GET parameter in the URL:
axios.get(URL_TICKETS_BY_USERID + "?id=" + user.userID, config)
In my case it was the question mark. In some database systems, the question mark is used as a placeholder for values that are passed in separately. However, it seems that in my case, the database system is not recognizing the question mark as a placeholder, and is interpreting it as part of the query.
So changed the query to:-
const q = `SELECT * FROM list WHERE userid = ${listId}`;
I passed the variable inside the query and it works now
Noob question. I'm trying to write an Apollo Server GraphQL resolver that will query and return a user from a MySQL database.
This is what I have so far:
const UserQueries = {
user: (_, args, { pool }) => {
let data = {};
pool.query(
"SELECT * FROM user_table WHERE `id` = ?",
[args.id],
(err, rows) => {
if (err) throw err;
else {
data.id = rows[0].id;
data.name = rows[0].name;
data.username = rows[0].username;
data.email = rows[0].email;
}
}
);
return data;
},
};
pool is the mysql2 connection pool. If I console log inside that else statement I am getting the correct data back from the database. The problem is I can't make it go into that variable. If I move the return statement inside the else statement it still doesn't work.
Definitely a noob question but I'm totally stuck. Thanks.
I think it should work, you should check your typedef, whether the response (data object fields) matches with the respective typedef fields or not.
I want to display data from MySQL database into html table. I write REST API in js file. I try to call in table rows. But it shows error
jquery-3.3.1.min.js:2 GET localhost:9000/api/addbooks/getbooktable net::ERR_CONNECTION_REFUSED
var books = function(req, res) {
const query = 'SELECT * FROM booklist';
connection.query(query, function(err, result) {
if (err) {
console.error(err);
return res.status(400).send(err);
}
return res.status(200).send(result);
});
};
You must import the mysql package first and then make a connection to the mysql database. You seem to be getting started with nodejs and mysql, check out the link below to learn how to connect to mysql through nodejs
Link: https://www.w3schools.com/nodejs/nodejs_mysql.asp
Npm package: https://www.npmjs.com/package/mysql
I'm trying to build a server in node.js that'll take a request from a client, access a mysql server on the server, and send data from that server to the client. I am able to access the mysql server outside of the createServer but I can't put the sql query within the createServer method.
Example of what doesn't work:
var jellies;
http.createServer(function (req, res) {
var sql = "SQL STATEMENT";
sqlConnection.query(sql, function(err, result) {
if (err) throw err;
jellies = result;
}
res.write(JSON.stringify(jellies));
}).listen(port);
Example of what does work:
var jellies;
var sql = "SQL STATEMENT";
sqlConnection.query(sql, function(err, result) {
if (err) throw err;
jellies = result;
}
http.createServer(function (req, res) {
res.write(JSON.stringify(
}).listen(port);
console.log(jellies) after the query is made produces null for the first function. Are you just not allowed to do anything in http.createServer()? Any ideas to work around this?
The error I get is: TypeError: First argument must be a string or Buffer. It calls back the the line for htts.createServer();
Can you please try this?
http.createServer(function (req, res) {
var sql = "SQL STATEMENT";
sqlConnection.query(sql, function(err, result) {
if (err) throw err;
res.write(JSON.stringify(result));
}
}).listen(port);
Figures the problem I worked on all yesterday would get solved by a friend online in a few seconds.
For the next person that might struggle with this all that needs to be fixed is moving res.write() and res.end() into the sql query function.
i'm new to NodeJS (duh!).
I know it executes functions asynchronous but I still cannot see what causes this phenomenon:
I am using the express and mysql modules and trying to execute an SQL query based on request parameters. It is supposed to be a simple validation API feature where the server is going to lookup a user in a database by listening on a specific URL for two request parameters (user and passwd).
The problem is that the SQL query always returns an empty object as result when I do this using the request parameters in the query.
However, if i hard code the query and run it outside the app.get(...) I get the desired result! But I need this to work on demand by request...
(I'm not intending to use GET-request later on, this example is for debugging purposes :))
What am i doing wrong here?
Here's my code:
// Server and Mysql setup here
var app = require('express').createServer(),
SERVER_PORT = 8080;
var Client = require('mysql').Client,
client = new Client(),
...
// User, password and database setup here, cropped out from this example //
// ...
function validateUser(user, passwd, callback) {
client.query('SELECT date FROM '+CUSTOMERS_TABLE+' WHERE email="'+user+'" AND passwd="'+passwd+'";',
function selectCb(err, results, fields) {
if (err) {
throw err;
}
console.log(fields);
callback(results);
});
}
app.get('/', function(req, res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
if((typeof query[REQ_PARAM_USER] != 'undefined' && typeof query[REQ_PARAM_PASSWD] != 'undefined')
&& (query[REQ_PARAM_USER] != '' && query[REQ_PARAM_PASSWD] != '')) {
validateUser(REQ_PARAM_USER, REQ_PARAM_PASSWD, function(results) {
console.log(results);
});
}
res.end("End")
});
app.listen(SERVER_PORT);
console.log('Server running at port '+SERVER_PORT);
Oh, and by the way, console.log(fields) outputs the correct fields! But why not the results?
You are passing the wrong parameters to validateUser:
validateUser(REQ_PARAM_USER, REQ_PARAM_PASSWD, // ...
What you really want:
validateUser(query[REQ_PARAM_USER], query[REQ_PARAM_PASSWD], // ...
Edit: A few other issues with your code:
You don't have to parse the url. Express does this for you, and the query is available as req.query.
You shouldn't throw in asynchronous code. It will give unexpected results. Instead, stick to the nodejs paradigm of passing (err, results) to all callbacks, and do proper error checking where you can -- i.e., in your verifyUser, pass along the error with the callback and check for errors in your get handler. Either res.send(500) (or something) when you get an error, or pass it along to the express error handler by calling next(err).
validateUser(query[REQ_PARAM_USER], query[REQ_PARAM_PASSWD], function(err, results) {
if(err) {
console.error(err);
res.send(500);
} else {
console.log(results);
res.send(results);
}
});
Never pass query parameters directly to something like an SQL query. Instead, use parameters for your SQL query:
client.query('SELECT date FROM '+CUSTOMERS_TABLE+' WHERE email=? AND passwd=?', [user, passwd], // ...