I am inserting multiple rows in a table with single insert query using the following format:
INSERT INTO $table (field1,field2) VALUES (value1,value2),(values3,values4);
The number of rows varies. Is there a way to use Perl's prepare statement for this kind of queries ?
For example, if I am inserting only one row I can do like the below:
$query = "INSERT INTO $table (field1,field2) VALUES (?,?)";
$sth = $dbh->prepare($query);
$sth->execute('value1','value2');
However, I want to do something like the below:
$values = '(value1,value2),(values3,values4),(values5,values6)';
$query = "INSERT INTO $table (field1,field2) VALUES ?";
$sth = $dbh->prepare($query);
$sth->execute($values);
Is this possible? or any other ways to achieve this ?
You can build up a query that can do what you want. Assuming that your records are in an array like this.
my #records = ( ['value1', 'value2'], ...) ;
Then you can create a query dynamically and execute it.
my $values = join ", ", ("( ?, ? )") x #records;
my $query = "INSERT INTO $table (field1,field2) VALUES $values";
my $sth = $dbh->prepare($query);
$sth->execute(map { #$_ } #$records);
Also in your example you are using string interpolation on the table name. Be careful with that as it can lead to database injections.
Put each record in its own array, then make an array of those:
my #records = ( [ 'value1', 'value2' ], [ 'value3', 'value4' ], [ 'value5', 'value6' ] );
Then prepare your INSERT statement:
my $query = "INSERT INTO $table (field1,field2) VALUES (?,?)";
my $sth = $dbh->prepare($query);
Then loop over your records and execute your statement handle for each one:
foreach my $rec ( #records ) {
$sth->execute( #$rec );
}
Related
I have two mysql queries to insert the data into two different tables. the result of the queries are as follows:
INSERT INTO table1 (ans1,ans2,ans3,ans4,ans5) VALUES (0,0,0,0,0),(1,1,1,0,0),(0,0,0,0,0)
INSERT INTO table2 (uid,cid,sid) VALUES (1,abc,123),(2,def,456),(3,ghi,789)
How can I concatenate these two results so that the output would look like
INSERT INTO table3 (uid,cid,sid,ans1,ans2,ans3,ans4,ans5)
VALUES
(1,abc,123,0,0,0,0,0),
(2,def,456,1,1,1,0,0),
(3,ghi,789,0,0,0,0,0)
I think something as this:
<?php
//First we need connect to database
$server = "localhost";
$Userdb = "admin";
$Passworddb = "password";
$database = "db";
$conn = mysqli_connect($server, $Userdb, $Passworddb, $database);
mysqli_set_charset($conn, "utf8");
//Getting values - for this example it is static
//For concate we need values as array => explode()
$colums1 = "ans1,ans2,ans3,ans4,ans5";
$values1 = explode("),(", substr("(0,0,0,0,0),(1,1,1,0,0),(0,0,0,0,0)", 1, -1));
$colums2 = "uid,cid,sid";
$values2 = explode("),(", substr("(1,abc,123),(2,def,456),(3,ghi,789)", 1, -1));
//Query for table1
$command = "INSERT INTO table1 (".$colums1.") VALUES ".$values1;
mysqli_query($conn, $command) or die(mysqli_error($conn));
//Query for table2
$command = "INSERT INTO table2 (".$colums2.") VALUES ".$values2;
mysqli_query($conn, $command) or die(mysqli_error($conn));
//We need to concate values so =>
//=> For every index of $values1 add at same index into $values3 concated $values1 and $values2
$values3 = array();
for ($x = 0; $x <= count($values1); $x++) {
$values3[$x] = "(".$values2[x].",".$values1[$x].")";
}
//Query for table3
$command = "INSERT INTO table3 (".$colums2.",".$colums1.") VALUES (".implode("),(", $values3).")";
mysqli_query($conn, $command) or die(mysqli_error($conn));
?>
I think that this SHOULD works (one never knows :) )
I'm breaking my brains over this, i would realy appriciate help!
This is the code i have so far..
$conn = db_connect();
$sql = "INSERT INTO measurements
(`date`, `weight`, `waist`, `id`) VALUES (?,?,?,?)";
$stmt = $conn-> prepare($sql);
$stmt ->bind_param("sddi", $date, $_POST['weight'], $_POST['waist'], $user_id);
$stmt->execute();
$stmt->close();
$conn->close();
Its a prepared statement for an sql insert. Now i want to change it to a IF EXIST THEN UPDATE ELSE insert the way i am doing right now. something like this but then with a prepared statement:
IF EXISTS
(SELECT * FROM measurements WHERE user_id=’4’)
UPDATE measurements SET (`weight`=40, `waist`=45) WHERE user_id=’4’
ELSE
INSERT INTO measurements
VALUES (`date`='week 1', `weight`= 40, `waist`=45, `id`=4)
I found some articles on stackoverflow about the if EXIST then update else insert but i did not find it with a prepared statement in it that worked for me.
Thanks a thousand!
UPDATE:
i've changed it to dublicate key style.
$sql = "
INSERT INTO measurements (uniqueID, date, weight, waist)
VALUES ('$uniqueID', '$date', '$weight', '$waist')
ON DUPLICATE KEY UPDATE weight= '$weight', waist= '$waist'";
$conn->query($sql);
Now the second part of the question, how do i make this a prepared statement?
To implement Mr. Jones' solution as a mysqli prepared statement, you would code it thus:
$sql = "INSERT INTO measurements
(`uniqueID`, `date`, weight, waist)
VALUES
(?, ?, ?, ?)
ON DUPLICATE KEY
UPDATE weight = ?, waist = ?";
$stmt = $conn->prepare($sql);
$stmt ->bind_param("isdddd", $user_id, $date, $_POST['weight'], $_POST['waist'], $_POST['weight'], $_POST['waist']);
$stmt->execute();
A slightly cleaner implementation would be to use PDO:
$sql = "INSERT INTO measurements
(`uniqueID`, `date`, weight, waist)
VALUES
(:uniqueId, :date, :weight, :waist)
ON DUPLICATE KEY
UPDATE weight = :weight, waist = :waist";
/* $conn is a PDO object */
$stmt = $conn->prepare($sql);
$stmt->execute(array(':uniqueId' => $user_id, ':date' => $date, ':weight' => $_POST['weight'], ':waist' => $_POST['waist']));
Note that with named placeholders, you can use the same name in more than one place and only need to assign the value once.
MySQL's approach to this is INSERT ... ON DUPLICATE KEY UPDATE .... It works well; in particular it avoids race conditions if more than one database connection tries to hit the same row.
This requires the table that's the target of your UPSERT to have a meaningful unique index or primary key. It looks like your id is that key.
You can absolutely use parameter binding to present data to this.
You can read about it here. http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
I want to insert the data I have in my grid in table 'quote' in my database, when I put this code in the trigger on ProcessMaker.
when I tried with a normal form it worked but if the grid it works I think it's a problem of syntax or foreach gridsizerows n is not, can someone please help me:
here is the code
$i=0 foreach ($i < $gridsizerows) {
$i = i +1;
$id = #mygrid [$i]['id'];
$quantity = #mygrid[$i]['quantity'];
$pu = #mygrid[$i]['possible'];
$pt = #mygrid[$i]['pt'];
$to = #mygrid [$i]['designation'];
$sql = "INSERT INTO quotes (id, designation, quantity, pu, pt) VALUES ($id, $from, $pu, $pt, $amount)";
$tmp_db = executeQuery($sql, '90911865253a802b030e577077431812');
}
Your code looks good, 2 possible changes you might want to do are as given below..
Instead of this:
$sql = "INSERT INTO quotes (id, designation, quantity, pu, pt) VALUES ($id, $from, $pu, $pt, $amount)";
Use this:
$sql = "INSERT INTO quotes (id, designation, quantity, pu, pt) VALUES ('$id', '$from', '$pu', '$pt', '$amount')";
and Instead of this:
$tmp_db = executeQuery($sql, '90911865253a802b030e577077431812');
Use this:
$dbConn = '90911865253a802b030e577077431812';
$tmp_db = executeQuery($sql, $dbConn);
I'm trying to do something that may be too complicated for MySQL
If a row exists i'd like it to update a counter and if not insert the row...I did a search and found this...
$query = "insert into TABLE
(`id`, `item`, `count`, `option1`, `option2`)
values
('$cartName', '$sku', 1, '$option1', '$option2')
on duplicate key
update count = count + 1";
but I don't have a key in the table so the "on duplicate key" won't work, the query needs multiple ANDs to check the row based on the id, item, and 2 option values.
an added thing is to have mySQL return a count of all count values based on the item
This is what I have currently (modified from search :), does anyone know how to reduce this into a single query?
option1 and option2 are variable and could be null so that's why the 2 if statements and is called from AJAX so the $message is used to update the javascript client side.
$query = "update TABLENAME set count=count+1 where item='$item'";
if($option1) $query .= " AND option1='$option1'";
if($option2) $query .= " AND option2='$option2'";
$result = mysql_query($query) or die("Error:".mysql_error() );
if (mysql_affected_rows()==0) {
$query = "insert into $table11 (`id`, `item`, `count`, `option1`, `option2`) values ('$id', '$item', 1, '$option1', '$option2');";
$result = mysql_query($query) or die("Error:".mysql_error() );
}
//total count for all items with specific id
$query = "SELECT SUM(count) FROM TABLENAME WHERE id='$cartName'";
$result = mysql_fetch_row(mysql_query($query)) or die("Error:".mysql_error() );
$message = $result[0];
I have a table of checkboxes and values, if a user selects a checkbox they select the value of the id in an array called checkedHW for simplicity sake this is what code looks like:
$ids = implode(',',arrayofids);
$sql = "insert into table(id, type) values($ids,type);
$db->query($sql);
echo query for testing:
"insert into table('id1,id2','type')
I figured that if I loop through this query I could hypothetically do this:
"insert into table('id1','type');"
"insert into table('id2','type');"
but I'm not exactly quite sure how to do, any help would be wonderful :)
I actually solved it using:
for($i=0;$i<count(arrayofids); $i++){
$sql = "insert into table(id,type) values(array[$i], 'type'";
$db->query($sql);}
I hope that helps someone and thank you guys for the help!
You could do something like this:
$base = 'INSERT INTO table (id, type) VALUES (';
$array = array(1, 2, 3, 4);
$values = implode(", 'type'), (", $array);
$query = $base . $values . ", 'type')";
$db->query($query);
This is what would be getting submitted:
INSERT INTO table (id, type) VALUES (1, 'type'), (2, 'type'), (3, 'type'), (4, 'type')
Both query are completely different
insert into table('id1,id2','type') will insert single row
id1,id2 | type
whereas
insert into table('id1','type');"
insert into table('id2','type');"
will insert two rows
id1 | type
id2 | type
so if your id column is int type then you cant run first query
If you have a series of checkboxes, and wanting to insert the values into your table, you could loop through them like this:
<?php
$values = array();
foreach ($_POST['field_name'] as $i => $value) {
$values[] = sprintf('(%d)', $value);
}
$values = implode(',', $values);
$sql = "INSERT INTO `table_name` (`column_name`) VALUES $values";
This will give you a SQL query similar to:
INSERT INTO `table_name` (`column_name`) VALUES (1),(2),(3),(4)
Hope this help.