WRONG_VALUE_COUNT_ON_ROW: But I can't see the problem? - mysql

I'm trying to insert data into MySQL via Express, the database table is created as such:
create table foods (name VARCHAR(100), typval DECIMAL(8, 2), unit VARCHAR(50), calories DECIMAL(5, 2), carbs DECIMAL(5, 2), fat DECIMAL(5,2), protein DECIMAL(5, 2), salt DECIMAL(5, 2), sugar DECIMAL(5, 2));
I have a form which collects user data and the function to post looks something like this:
app.post("/addnewfood", function (req,res) {
console.log(req.body.name, req.body.typval, req.body.unit, req.body.calories, req.body.carbs, req.body.fat, req.body.protein, req.body.salt, req.body.sugar);
// saving data in database
let sqlquery = "INSERT INTO foods (name, typval, unit, calories, carbs, fat, protein, salt, sugar) VALUES (?,?)";
// execute sql query
let newrecord = [req.body.name, req.body.typval, req.body.unit, req.body.calories, req.body.carbs, req.body.fat, req.body.protein, req.body.salt, req.body.sugar];
db.query(sqlquery, newrecord, (err, result) => {
if (err) {
return console.error(err.message);
}else
res.send("New" + " " + req.body.name + " was added to the database.");
});
});
I'm not sure where I'm going wrong since I counted there's 9 different fields I need to fill in for the 9 different columns. I've checked the commas and I can't see anything out of place.
When I try to enter data like: "McDonalds Hamburger, 1.0, Burger, 100.00, 10.00, 10.00, 10.00, 1.0, 10.00"
The console.log prints it out fine and it should work however, I get:
ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1
Help?

Your INSERT query needs a placeholder for every column you insert. You only have two placeholders -- two ? items -- here.
VALUES (?,?)
You need nine, one for each column.
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)

Related

Insert Record into Table Wrong Syntax for MySQL Query

I am trying to insert a record into my MySQL table. When I submit my form, it puts a post request to '/admin', which inserts the posted data into the events table.
However, instead of inserting the record, the query keeps on giving me an error, because of Error: ER_PARSE_ERROR. To fix this, I looked at many sample insert queries for mysql, but I still do not know what I am doing wrong. Can someone give me a hand with this? Thank you!
Image of Error:
Image of mySQL table structure:
app.post('/admin', upload.none(), function(req, res) {
//store the event
var event_date = convertDateFormat(req.body.date);
var start_time = convertTimeStringTo24Hours(req.body.starttime);
var end_time = convertTimeStringTo24Hours(req.body.endtime);
var sql =
"INSERT INTO events"
+ " (name, description, start_time, end_time, location, max_capacity, hidden_sign_up, other)"
+ " VALUES ?";
var values = [
req.body.eventname,
req.body.description,
event_date + " " + start_time,
event_date + " " + end_time,
req.body.location,
req.body.attendee,
0,
""
];
con.query(sql, values, function(err, result) {
if (err) throw err
res.redirect('/admin')
});
});
You need as many parameters as there are values to insert in the table, enclosed with parenthesis.
So you would need to replace this:
var sql =
"INSERT INTO events"
+ " (name, description, start_time, end_time, location, max_capacity, hidden_sign_up, other)"
+ " VALUES ?";
With:
var sql =
"INSERT INTO events"
+ " (name, description, start_time, end_time, location, max_capacity, hidden_sign_up, other)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
As far as concerned you don't need to change the rest of your code (bind parameters should be passed as an array, which you are already doing).

How do I hash and salt a password into mysql database using a servlet?

Here is what I have from my servlet
Random random = new Random();
String salt = Integer.toString(random.nextInt(1000000000 - 1 + 1) + 1);
String sql = "insert into users (user_name, salt, password) "
+ "values (?, ?, ?)";
c = DriverManager.getConnection( url, username, password );
PreparedStatement pstmt = c.prepareStatement( sql );
pstmt.setString( 1, userName );
pstmt.setString( 2, salt);
pstmt.setString( 3, "SHA2(CONCAT('" +password1+ "', "+ salt +"), 256)");
The values for the username and password are stored correctly on the server but the password is not. It is stored as the following SHA2(CONCAT('edf', 733903552), 256) for the given values.
I am assuming the SHA2 and CONCAT function are not taking effect, been playing around with it for a while and can't figure out why.
It's a string literal being passed, and that's what's being stored. Consider:
String foo = "SHA2(CONCAT('" +password1+ "', "+ salt +"), 256)";
pstmt.setString( 3, foo );
The value of foo is what gets passed in as a value in the SQL statement.
MySQL doesn't see any of the contents of that string as SQL text... it's just a string. (This is behavior that we want. One of the big benefits of prepared statements and bind placeholders is preventing SQL injection, that is, preventing values from being interpreted as part of the SQL.)
If you want the CONCAT and SHA2 functions executed as MySQL functions, those need to be part of the SQL text. Pass in (as values) just password1 and salt.
Something like this:
String sql = "insert into users (user_name, salt, password)"
+ " values (?, ?, SHA2(CONCAT( ? , ? ),256) )";
pstmt.setString( 1, userName );
pstmt.setString( 2, salt );
pstmt.setString( 3, password1 );
pstmt.setString( 4, salt );

Use of `if( ... = ... )` in mysql?

insert into foo_table (fname, lname, number)
values ('John', 'Doe', if(123 = 456));
For the above MySQL query, can somebody kindly explain what the if(123 = 456) is doing? I currently struggle to see an if statement without a body (i.e. if(condition){ // do something });
The query is syntactically not correct as per mysql version 8, The syntactically correct query is insert into foo_table (fname, lname, number) values ('John', 'Doe', if(123 = 456,1,2)). This will insert 1 if the condition (123 =456) is true, otherwise it will insert 2.

MySQL performing math operations on strings?

I am trying to store latitude and longitude information in MySQL. I am using Ruby to parse the latitude and longitude data. They are parsed separately and then combined into a string variable. So if I have:
latitude = 43.78219.to_s
longitude = -75.00326.to_s
location = latitude + " " + longitude # => "43.78219 -75.00326"
I have a table in MySQL to store this data, and the data type is set to String varchar. The problem is that when I insert the location string into the table, MySQL performs a math operation and subtracts the two numbers in the string. Then I'm like Whaaaaaaaaa???????
So it ends up storing -31.22107 as the location. Am I doing something wrong?
Here is the query I'm using
db.query("insert into StationCapacityStatus
(city_id, station_id, location, empty_docks, nonempty_docks, timestamp)
values(
23,
#{$station_number},
#{location},
#{$empty_docks},
#{$nonempty_docks},
#{$datetime}
)"
)
You're not quoting the location so MySQL's sees a plain 43.78219 -75.00326 inside the VALUES and interprets it as a floating point expression. You should use quote method to properly escape the strings as well:
db.query("insert into StationCapacityStatus
(city_id, station_id, location, empty_docks, nonempty_docks, timestamp)
values(
23,
#{$station_number},
'#{db.quote(location)}',
#{$empty_docks},
#{$nonempty_docks},
#{$datetime}
)"
)
You should also switch to prepared statements with bound values if possible:
sth = db.prepare('insert into StationCapacityStatus (city_id, station_id, location, empty_docks, nonempty_docks, timestamp) values (?, ?, ?, ?, ?, ?)')
sth.execute(23, $station_number, location, $empty_docks, $nonempty_docks, $datetime)

INSERT INTO with subquery & parameters not working in MS-Access

I have an INSERT INTO which works fine with the parameters as constants:
INSERT INTO FinalValidityCodes
(tblReceivedSamplersID, Substudy, Location, FinalValidityCode, DateTimeProcessed)
SELECT ID, true, 'I', 0, now()
FROM tblReceivedSamplers
WHERE (SampleID = ?)
This would affect 1 row (as expected)
Yet if I change the query to use parameters it will allow it to run but will never affect any rows.
INSERT INTO FinalValidityCodes
(tblReceivedSamplersID, Substudy, Location, FinalValidityCode, DateTimeProcessed)
SELECT ID, ?, ?, ?, ?
FROM tblReceivedSamplers
WHERE (SampleID = ?)
What is the difference and why, when I use parameters, does the Insert, seemingly, fail?
Edit:
SampleID is a text datatype.
It looks like the purpose of that INSERT is to add a single row to FinalValidityCodes with values for 5 fields. However, 4 of those values will be supplied directly by query parameters, and ID/tblReceivedSamplersID will be derived from another parameter.
So I would try a DLookup() expression to get the ID (using the parameter for SampleID), and insert that value along with the other 4 parameter values. Here is an untested guess.
INSERT INTO FinalValidityCodes (
tblReceivedSamplersID,
Substudy,
Location,
FinalValidityCode,
DateTimeProcessed
)
VALUES (
DLookup("ID", "tblReceivedSamplers", "SampleID ='" & param1 & "'"),
param2,
param3,
param4,
param5
);