Inserting data into the mysql database from perl - mysql

I am trying to insert data into a MySQL database:
$response = $client->fql->query(
query => '
SELECT name, email, birthday, username, first_name, last_name, pic
FROM user
WHERE uid = me()
',
);
print join "\n Name:", sort map { $_->{name} } #$response;
$dbh->do("
INSERT INTO Users(SNo,Name,Email,Birthday,UserName,FirstName,LastName)
VALUES(1,
sort map { $_->{name} } #$response,
'imm\#gmail.com',
'1987/12/10',
'imm',
'imm',
'Dee')
");
$dbh->disconnect();
used the mysql query in one line.
This above print statement is printing the name correctly but why the above sql insert statement is not working?
I connect the db and after that i am receiving the value and printing in the browser is working.
Why does the mysql statement not accept the value?
When inserting the database is not working?

You should have a look at the official doc
and specially this :
# INSERT some data into 'foo'. We are using $dbh->quote() for
# quoting the name.
$dbh->do("INSERT INTO foo VALUES (1, " . $dbh->quote("Tim") . ")");
# Same thing, but using placeholders
$dbh->do("INSERT INTO foo VALUES (?, ?)", undef, 2, "Jochen");

Related

Inserting a variable into MySQL with Go

I have these 2 variables here
name := request.FormValue("username")
pass := request.FormValue("password")
I want to insert those 2 variables into my database
db.Query("INSERT INTO `godb` (`Username`, `Password`) VALUES ( )")
I tried (name,pass) ('name','pass') ($name, $pass) , none of them work.
Hope the question is not stupid, but I've been looking for solutions online but I did't understand them. Thanks !
From Using Prepared Statements
Parameter Placeholder Syntax
The syntax for placeholder parameters in prepared statements is
database-specific. For example, comparing MySQL, PostgreSQL, and
Oracle:
MySQL PostgreSQL Oracle
===== ========== ======
WHERE col = ? WHERE col = $1 WHERE col = :col
VALUES(?, ?, ?) VALUES($1, $2, $3) VALUES(:val1, :val2, :val3)
You tried PostgreSQL syntax but you use MySQL.
query should be in this format
db.Query("INSERT INTO table ($1, $2) VALUES (column1, column2)", value1, value2)
in your case something like that
db.Query("INSERT INTO godb ($1, $2) VALUES (username, password)", name, pass)

WRONG_VALUE_COUNT_ON_ROW: But I can't see the problem?

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 (?, ?, ?, ?, ?, ?, ?, ?, ?)

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 );

Perl many insert statments into mysql database

I currently have code for perl that looks like this:
#valid = grep { defined($column_mapping{ $headers[$_] }) } 0 .. $#headers;
...
my $sql = sprintf 'INSERT INTO tablename ( %s ) VALUES ( %s )',
join( ',', map { $column_mapping{$_} } #headers[#valid] ),
join( ',', ('?') x scalar #valid);
my $sth = $dbh->prepare($sql);
...
my #row = split /,/, <INPUT>;
$sth->execute( #row[#valid] );
(Taken from mob's answer to a previous question.)
That is basically dynamically building a sql insert statement from csv data, and only allowing the csv data with proper headers from my column mapping to be picked.
I have been looking for examples on how to do an insert statment with multiple rows of data at once.
My perl script needs to run around a few hundred million insert statments, and doing it one at a time seems really slow, especially since the server I am running it on only has 6gb of ram and a slowish internet connection.
Is there a way I can upload more than 1 row at a time of data? So one insert statment uploads maybe 50 rows, or 100 rows at once? I cant find out how with perl DBI.
my $sql_values = join( ' ', ('(?, ?, ?)') x scalar(#array) );
As said before, then you can just flatten it.
You can insert multiple rows at once with the same syntax as in regular SQL, but you need to build your INSERT statemtent properly with Perl. Perl's slice() may help you:
Suppose you have 7 rows of data and want to insert them in chunks of 3 rows. "Regular" SQL would be like so:
insert into T (col1, col2) values ( 1, 2), ( 3, 4), ( 5, 6);
insert into T (col1, col2) values ( 7, 8), ( 9,10), (11,12);
insert into T (col1, col2) values (13,14);
Let's suppose your perl structure is like this:
my $values = [ [1,2], [3,4], ..., [13,14] ];
If it's not, bring it into this shape. Now:
use constant CHUNKSIZE => 3;
my $stmt = sprintf( 'insert into T (col1, col2) values %s',
join(',', '(?,?)' x CHUNKSIZE) );
# $stmt is now 'insert into T (col1, col2) values (?,?),(?,?),(?,?)'
my $sth = $dbh->prepare($stmt);
while( my #chunk = splice( #{$values}, 0, CHUNKSIZE ) ) {
# #chunk has 3 elements (rows), or less for the last chunk
if (scalar #chunk == CHUNKSIZE) {
$sth->execute( #chunk ); # inserts 3 rows at once
} else {
# build and prepare a new statement for the remaining rows.
# in our sample there is only 1 remaining row.
$stmt = sprintf( 'insert into T (col1, col2) values %s',
join(',', '(?,?)' x scalar #chunk) );
$sth = $dbh->prepare($stmt);
$sth->execute( #chunk ); # inserts the last row
}
}

mysql Undefined index on dynamic query

I have a database table that stores values to be used in a dynamic query, which pulls data from a table name stored in another column. For examples, one entry might be:
selects | tableName
-----------------------------------------------------------------------
fName,lName,email,phone,address,city,state,zip | foobar
I then take this value and use it to generate a dynamic query then i then run with my db class... something like this:
$fields = $connection->runQuery("SELECT selectItems, tableName FROM foo;");
$query = "SELECT " . $fields[0]['selectItems'] . " FROM " . $fields[0]['tableName'] . ";";
$results = $connection->runQuery($query);
That works fine, but if i try to change the selects values to something like this:
selects | tableName
-----------------------------------------------------------------------------------------------
CONCAT(fName, ' ', lName) as fullName,email,phone,address,city,state,zip | foobar
I get an error saying:
Undefined index: CONCAT(fName, ' ', lName) as fullName
How can i make it run the $query variable as if I had typed it in myself?
Here's a C/P of one of the "selects" values straight from the DB:
visitTimestamp as visitTS,firstName,lastName,CONCAT(apptDate,apptTime) as apptTS,address,phone,email,currentCarYear,currentCarMake,currentCarModel,currentCarValue,personID
When I do echo $query, I'm shown the following:
SELECT visitTimestamp as visitTS, firstName, lastName, CONCAT(apptDate, apptTime) as apptTS, address, phone, email, currentCarYear, currentCarMake, currentCarModel, currentCarValue, personID FROM foo
I copied and pasted the echoed $query string and ran it through phpMyAdmin and it worked just fine. Any ideas why it wouldn't be running when it's executed as a variable?