Why my database displays undefined even I inserted data in POSTMAN? - mysql

Below is my code for inserting data in MYSQL in ExpressJS.
router.post('/user', function (req, res) {
let sql = "INSERT INTO Member (id, Memb_ID, First_Name, Middle_Name, Last_Name, Address, url) VALUES (null, '" + req.body.Memb_ID + "', '" + req.body.First_Name + "', '" + req.body.Middle_Name + "', '" + req.body.Last_Name + "', '" + req.body.Address + "', '" + req.body.url + "')";
myDB.query(sql, function (err, results) {
if (err) throw err;
res.send({
Success: "Data inserted."
})
});
});
It inserts data in my database but my database looks like this
I don't know why it outputs like that. Here's my JSON
EDIT :
Here is my MYSQL Table

Can you make sure that the following is done?
The content-type header in the request has to be application/json
Use body-parser (or similar libraries) to parse JSON payloads -> You can print the req.body to validate this.
If you can confirm that the values are accessible, I would suggest escaping query values as mentioned in https://github.com/mysqljs/mysql#escaping-query-values (or in any mysql library that you use) - especially since it is a DML query.
(Also I assume that the fieldnames used in the query match with the ones in the database and are of the right datatype.)

In your image of postman call, it's clearly showing your content type is text.
Change Content-type to application/json in your postman call headers
Or you can select from body tab
As your body content was text as shown in your image, it was sending a plain text that leading to undefined in DB. But the server was expecting json.
Hope that helps.

See wether you have added #RequestBody annotation in your respective method signature in Controller...
check this 1's bcz i had same issue i resolved after adding this..
it may help you and others... also...

Related

How to insert file path into mysql table using nodejs

I am currently using mutler to upload the files to the server. Below is my query:
var insertSQL = "INSERT INTO ic_photos (icFrontURL,icBackURL,selfieURL,customer_id) VALUES ('" + frontICPath + "','"+backICPath + "','" + selfiePath + "','" + customerID + "')";
Console.log returns
"INSERT INTO ic_photos (icFrontURL,icBackURL,selfieURL,customer_id) VALUES ('public\images\frontIC_1526709299585_potato.png','public\images\backIC_1526709299595_potato2.jpg','public\images\selfie_1526709299596_potato3.jpg','41')"
But when it goes into mysql table, it shows the following value:
'publicimagesfrontIC_1526709040516_potato.png'
The slashes are missing. How can I fix this when I make the insert query ?
This replaces the backslash with two backslashes. When it got inserted into the table, it will become one backslash
frontICPath = frontICPath.replace(/\\/g, "\\\\");
In most, if not all string-based interpretation environments, a backslash is considered a special character. To use a backslash explicitly, please use: "\\".
The two slashes above consist of 4 slashes in total through the text editor.

MySQL Statement error in JSP

I have an issue with an sql statement and i dont know how to handle it. Here is the problem:
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")')";
The values are obtained from the post form which contains free text. The problem is, whenever a user enters characters like ', i will get an error because that tells the compiler that the value is over here(i suppose) and now look for the next value. I don't know how to include these characters and send them to database without having an error. Any help would be appreciated. Thank you.
The character ' is used to surround literals in MySQL. And if any data contains such character as part of it, we have to escape it. This can be done using Prepared Statement in Java.
Change your query code accordingly.
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`)
VALUES ( ?, ?,? )";
Now define a PreparedStatement instance and use it to bind values.
PreparedStatement pst = con.prepareStatement( query );
pst.setString( 1, session.getAttribute("id") );
pst.setString( 2, request.getParameter("RunningProjects") );
pst.setString( 3, request.getParameter("MainOrders") );
int result = pst.executeUpdate();
And, I suggest use of beans to handle business logic.
change
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")
+ "')";
I think you are using normal statement in your JDBC code. Instead, I would suggest you to use Prepared statement. Prepared statement is generally used to eliminate this kind of problem and caching issue. If you will use prepared statement I think your problem will be solved

INSERT INTO error with mysql-node

This seems like it should be super easy, and I have been stuck for about two hours now. Four separate people have looked at and not found an obvious problem. So again I turn to the SO community.
Real simple - I am just trying to insert data in a mysql database via mysql-node. I am getting no connection errors, and SELECT works just fine. The code being used is:
exports.postNewCast = function(data, res) {
var query = "INSERT INTO cast (name, portrait, role, bio) VALUES ('" + data.name + "', '" + data.portrait + "', '" + data.role + "', '" + data.bio + "');";
console.log(query);
dbConnection.query(query, data, function(err, result) {
if (err) {
console.log(err);
} else {
sendResponse(res, "Cast Member Added", 201);
}
});
};
The error being logged is:
{ [Error: ER_PARSE_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 'cast (name, portrait, role, bio) VALUES ('Jessie', 'images/cast/marissa.jpg', 'L' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0 }
The weird part (for me) is that I can copy from my terminal window (where the server is running) the console.logged query string, and paste it into the mysql command line, and it works just fine. I have tried using GRANT to make sure the user server is running has permissions, and this did nothing. I have tried copying / pasting INSERT INTO syntax straight from working sources, and only replacing my data-specific fields. I have tried using the VALUES ? option, followed by a data object, and got the same result.
So what stupid mistake am I making?
Thanks.
Ilya Bursov had it correct, adding this answer for posterity. I am not sure if 'cast' is a reserved word or what, but I needed back ticks (" ` ") around the table name to get it working.
Try to put `` around each column name like this
"INSERT INTO cast (`name`, `portrait`, `role`, `bio`) VALUES ('" + data.name + "', '" + data.portrait + "', '" + data.role + "', '" + data.bio + "');";

Does PreparedStatement convert empty strings to null?

I'm working with MySQL and their last available JDBC driver, on a User table with NOT NULL constraints on all its fields, which are id, name, password and email.
In my Java EE application, I first called a simple Statement this way :
statement = connection.createStatement();
statement.executeUpdate( "INSERT INTO User (name, password, email) "
+ "VALUES ('" + paramName + "', '" + paramPassword + "', '" + paramEmail + "');" );
Where paramName, paramPassword and paramEmail are strings. I passed empty strings to this request, and a new line with empty values got successfully inserted in the table, since MySQL considers empty strings different than null entries.
Then, I used a PreparedStatement instead :
preparedStatement = connection.prepareStatement( "INSERT INTO User (name, password, email) VALUES(?, ?, ?);" );
preparedStatement.setString( 1, paramName );
preparedStatement.setString( 2, paramPassword );
preparedStatement.setString( 3, paramEmail );
preparedStatement.executeUpdate();
But this time, when I passed empty strings to the request, I got the following error :
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'name' cannot be null
So here's my question : does the PreparedStatement, or maybe its setString() method, convert empty strings to null values? I looked it up and didn't find any information about this behavior in the javadoc.
The documentation of java.sql.PreparedStatatement didn't say anything about this in the method setString. I take a look at the sources of the MySQL ConnectorJ and I didn't find anything too. Are you sure that your String is not null?
The answer is NO. Please make sure that the value of your parameters are not null. Maybe your variable paramName is NULL.

Can't access object properties

I am using NodeJS and node-mysql, I've created a DB layer to allow easy integration with other DBs (example MongoDB) for later use. At this point in time, the syntax is essentially the same as MySQL.
I am placing a call to the query object of MySQL, and it's returning the results to my callback function, which I can send to the console with console.log, and it shows the following:
[ { username: 'test', total: 1 } ]
Yet, when I try to access the total, it says undefined. Here's my code:
db.query("SELECT username, COUNT(user_id) AS total FROM users WHERE username = '" + message.username + "'", function(err, info) {
console.log(info);
self.sendRequest(client, '{ "command" : "CALLBACK", "result" : ' + info.total + ' }');
});
when using console.log(info), it returns valid JSON syntax, however I cannot access the total via info.total, as it returns undefined....
Any ideas on why I'm having this issue? If you need to see more code I will be happy to provide it..
Figured it out;
info[0].total returns what I need (d'oh)...