how do i do bulk insert or update statements in mysql - php

i know there is a bulk insert in PHP that i can resolve easily in php
$list = array();
foreach($list as $key->$value){ $list[] = "($key, $value)"; }
$query = "insert into tblTest (a, b, c) values ".implode(",", $list);
$r = mysql_query($q);
and i know how to do a insert or update statement:
$insert into tblTest (a,b,c) values (1,2,3) on duplicate key update b=5;
I was not sure if this was the sufficient answer query i would want to run:
INSERT INTO tblTest (a, b, c)
VALUES(1, 2, 3) ON DUPLICATE KEY UPDATE b=VALUES(b), c=VALUES(c)

Related

How to insert array of array in phpmyadmin using php

I am trying to insert an array of row in database and every row of array contain 3 another rows.
foreach($type as $a=>$b)
{
$sql="INSERT INTO `actual_regular` (`employee`, `sex`, `caste`, `family`, `local`, `worked_month`, `incash`, `total_salary`) VALUES ('$type[$a]', '$sex_actual[$a]', '$caste_actual[$a]', '$family_actual[$a]', '$employee_actual[$a]', '$worked_month[$a]', '$cash_actual[$a]', '$salary_actual[$a]');";
mysql_query($sql);
Above will insert array of rows. Every rows contain 3 rows that will be inserted in new table
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ('$detail_product[0]', '$unit[0]', '$quantity[0]', '$price[0]');";
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ( '$detail_product[1]', '$unit[1]', '$quantity[1]', '$price[1]');";
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ('$detail_product[2]', '$unit[2]', '$quantity[2]', '$price[2]');";
mysql_query($insert);
} // above foreach ends here
I mean there are multiple rows need to be inserted in table actual_regular every rows contain 3 more rows. These 3 rows are inserted in table more_regular.
Use single insert query for three insert operations like this:
<?php
$insert = "INSERT INTO `more_regular` (`product_detail`, `unit`, `quantity`, `price`) VALUES ";
$values = array();
foreach ($type as $a=>$b) {
$values[] = "('$detail_product[0]', '$unit[0]', '$quantity[0]', '$price[0]')";
$values[] = " ( '$detail_product[1]', '$unit[1]', '$quantity[1]', '$price[1]')";
$values[] = " ('$detail_product[2]', '$unit[2]', '$quantity[2]', '$price[2]')";
} // above foreach ends here
if (! empty($values)) {
$insert .= implode(', ', $values);
}
mysql_query($insert);
?>
Basically, the logic is:
INSERT INTO TABLE (ID, NAME) VALUES
(1,'Andrew'),
(2,'Glenn'),
(3,'Marvel');

insert single set of data multiple times mysql

I have to insert single set of data multiple times , say n rows.
INSERT INTO MyTable VALUES ("John", 123, "US");
Can I insert all n rows in a single SQL statement?
here n is dynamic value n is user input , how to make insert query n times , any idea.
$sql = "INSERT INTO `mytable` VALUES(`field1`,`field2`,`field3`) VALUES ";
$count = 5;
for($i=0;$i<$coutn;$i++)
{
$sql .= " ('john','123','us' )";
}
is this correct way..
Yep, this can be done easily, it should look something like this:
INSERT INTO MyTable VALUES ("John", 123, "US"), ("Carl", 123, "EU"), ("Jim", 123, "FR");
However, it is good programming practice to specify the columns of your table in the query, for example:
INSERT INTO MyTable (Column1, Column2, Column3)
VALUES ("John", 123, "US"), ("Carl", 123, "EU"), ("Jim", 123, "FR");
EDIT : You can build your query like this (in for cycle), the $total is your user input:
$sql = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES";
//Build SQL INSERT query
for ($i = 1; $i <= $total; $i++) {
$sql .= " ($value1, $value2, $value3), ";
}
//Trim the last comma (,)
$sql = rtrim($sql,",");
//Now, the $sql var contains the complex query.
$result = mysql_query($sql);
As you can see we do not execute the INSERT statement in the loop, but rather we build the SQL query text and then we will execute it in one pass.

Simple ON DUPLICATE KEY UPDATE?

I'm trying to store a one-to-many relationship in my mySQL database and I want to avoid duplicate entries if at all possible.
I read on the internet and saw that 'ON DUPLICATE KEY UPDATE' is an option. Would this work for my situation?
CODE:
function insert_options($uid, $array) {
if(!is_array($array)) {
return false;
}
$db = db_connect();
foreach($array as $a) {
$sql = 'INSERT INTO newsletter_coupon_codes_options (uid, option_name, value) VALUES (?, ?, ?)';
$stmt = $db->prepare($sql);
if($stmt === false) {
echo "Prepare failed: (" . $db->errno . ") " . $db->error;
}
$stmt->bind_param('iss', $uid, $a, $value);
$value = '1';
$stmt->execute();
}
}
TABLE
UID(INT11), OPTION_NAME(varchar(255)), VALUE(INT(11))
I tried to add ON DUPLICATE KEY UPDATE value = 1 to the $sql statement, but it didn't seem to do anything. Basically I want to make sure when I'm inserting the data if the uid and option_name exist, it just sets the value to 1 and doesn't make a new entry.
I do not have a unique key set up, only a primary key on uid. I wasn't sure what to make unique. I can't make the uid unique, as there will be multiple entries per uid. I also cannot make the option_name unique as there will be the same option_name for multiple uid's
What is the best way to accomplish this?
Change your query to
INSERT INTO newsletter_coupon_codes_options (uid, option_name, value)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE value = VALUES(value)
Here is SQLFiddle demo
And make sure that you have a UNIQIE or PRIMARY KEY constraint on (uid, option_name), e.g.
ALTER TABLE newsletter_coupon_codes_options
ADD UNIQUE (uid, option_name);
Please change your query like this and use mysqli_query function execute this kindof queries and use mysqli_real_escape_string function to avoid SQL injections
$sql = 'INSERT INTO newsletter_coupon_codes_options
(uid, option_name, value) VALUES ("'.$uid.'", "'.$option_name.'", "'.$value.'")
ON DUPLICATE KEY UPDATE value = "'.$value.'"';

Insert multiple rows with PDO prepared statements

I would like to know if it is possible to insert multiple rows using one prepared statement.
Below is an example of how I would normally insert one row into the db:
$params=array();
$params[':val1']="val1";
$params[':val2']="val2";
$params[':val3']="val3";
$sql="INSERT INTO table VALUES (col1,col2,col3) VALUES (:val1,:val2,:val3)";
$stmt=DB::getInstance()->prepare($sql);
$stmt->execute($params);
The values I want to insert will come from an array, for example:
$values[0]['val1'];
$values[0]['val2'];
$values[0]['val3'];
$values[1]['val1'];
$values[2]['val2'];
etc.
This code may have to insert a few hundred rows at once, I thought about creating a loop to create hundreds of params and then append the sql statement with an extra insert for each row but I thought there must be a better way. What would be the best way to do this?
The first important thing to say is that you can insert multiple rows thanks to only one INSERT query
INSERT INTO Table (col1, col2, col3)
VALUES ('abc', 'def', 'ghi'),
('abc', 'def', 'ghi'),
('abc', 'def', 'ghi'),
('abc', 'def', 'ghi'),
('abc', 'def', 'ghi')
-- and so on...
Once you know that, you're able to get a good solution with PDO (for instance).
You have to keep in mind that you want a complete prepare and execute process (in term of security, you have to pass each parameter separately).
Let's say you have rows to insert structured as follow:
$rows = array(
array('abc', 'def', 'ghi'), // row 1 to insert
array('abc', 'def', 'ghi'), // row 2 to insert
array('abc', 'def', 'ghi') // row 3 to insert
// and so on ...
);
Your goal is to have this result as a prepared query:
INSERT INTO Table (col1, col2, col3)
VALUES (?, ?, ?),
(?, ?, ?),
(?, ?, ?)
With its corresponding execute:
PDOStatement::execute(array('abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi'));
Well, you only have to do it now:
$rows = array(
array('abc', 'def', 'ghi'),
array('abc', 'def', 'ghi'),
array('abc', 'def', 'ghi')
);
$row_length = count($rows[0]);
$nb_rows = count($rows);
$length = $nb_rows * $row_length;
/* Fill in chunks with '?' and separate them by group of $row_length */
$args = implode(',', array_map(
function($el) { return '('.implode(',', $el).')'; },
array_chunk(array_fill(0, $length, '?'), $row_length)
));
$params = array();
foreach($rows as $row)
{
foreach($row as $value)
{
$params[] = $value;
}
}
$query = "INSERT INTO Table (col1, col2, col3) VALUES ".$args;
$stmt = DB::getInstance()->prepare($query);
$stmt->execute($params);
And... That's it!
This way, each param is treated separately, which is what you want (security, security, security!) and all of it, in a dynamic way, with only one INSERT query
If you have too many rows to insert (see this), you should execute one by one
$rows = array(
array('abc', 'def', 'ghi'), // row 1 to insert
array('abc', 'def', 'ghi'), // row 2 to insert
array('abc', 'def', 'ghi') // row 3 to insert
// and so on ...
);
$args = array_fill(0, count($rows[0]), '?');
$query = "INSERT INTO Table (col1, col2, col3) VALUES (".implode(',', $args).")";
$stmt = $pdo->prepare($query);
foreach ($rows as $row)
{
$stmt->execute($row);
}
If your table is transactional (for example an InnoDB), you can use a Transaction to speed up your insertions. A transaction has also the advantage of roll backs.
$pdo = DB::getInstance();
$stmt = $pdo->prepare('INSERT INTO table VALUES (col1, col2, col3) VALUES (:val1, :val2, :val3)');
$pdo->beginTransaction();
// The queries are not executed yet, but pushed to a transaction "stack"
foreach ($values as $value) {
$stmt->execute([
':val1' => $value['val1'],
':val2' => $value['val2'],
':val3' => $value['val3'],
]);
}
// Executes all the queries "at once"
$pdo->commit();
If you're only inserting a few hundred rows, I'd favor simpler code like the following. Prepare a single-row INSERT statement, and then loop over your data array, executing the prepared query once for each row.
$rows = array(
array('abc', 'def', 'ghi'), // row 1 to insert
array('abc', 'def', 'ghi'), // row 2 to insert
array('abc', 'def', 'ghi') // row 3 to insert
// and so on ...
);
$params = implode(",", array_fill(0, count($rows[0]), "?"));
$sql = "INSERT INTO mytable VALUES ($params)";
$stmt = $pdo->prepare($sql); // rely on exceptions for error detection
foreach ($rows as $row) {
$stmt->execute($row);
}
MySQL does support multi-row INSERT syntax of course, so you could try putting that together.
$params = implode(",", array_fill(0, count($rows[0]), "?"));
$tuples = "(" . implode("),(", array_fill(0, count($rows), $params)) . ")";
$sql = "INSERT INTO mytable VALUES $tuples";
$values = call_user_func_array("array_merge", $rows);
$stmt = $pdo->prepare($sql);
$stmt->execute($values);
But if you try to create a single INSERT statement with as many tuples as the items in your data array, you might accidentally generate an SQL statement that is longer than the maximum packet length.
If you have thousands of rows, enough so that executing a prepared statement one row at a time is too much overhead, you should use LOAD DATA INFILE.
To keep your code, you have to make a loop for executing all insertions you need :
$array_params = array();
$params[':val1']="val1 1";
$params[':val2']="val1 2";
$params[':val3']="val1 3";
$array_params[] = $params;
$params[':val1']="val2 1";
$params[':val2']="val2 2";
$params[':val3']="val2 3";
$array_params[] = $params;
$sql="INSERT INTO table (col1,col2,col3) VALUES (:val1,:val2,:val3)";
$stmt=DB::getInstance()->prepare($sql);
foreach($array_params as $params)
{
$stmt->execute($params);
}
But its possible to execute multiple insertions with one query like INSERT INTO table (col1,col2,col3) VALUES ("val1","val2","val3"),("val4","val5","val6"),("val7","val8,"val9"), by using something like this to build the query:
$all_inserts = array( array('val1', 'val2', 'val3'),array('val4', 'val5', 'val6'));
$sql = 'INSERT INTO table (col1,col2,col3) VALUES ';
$rows = array();
foreach ($all_inserts as $one_insert)
{
$rows[] = '('.implode(',', $pdo->quote($one_insert).')';
}
$sql .= ' '.implode(',', $rows);
$pdo->query($sql);

Insert query does't insert data to mysql database table

i have a recipe table and ingredient table the primary key of both tables are auto increament and primary key of recipe is foreign key in ingredient. i post data from html to php.Note that my ingredient textboxes are generated dynamically and successfully post the data to php script. posted data is correct when i insert this data to table my query working fine but data is not added to mysql table. my code and output is
$sql = "insert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', '$name','$overview','$category','$time','$TARGET_PATH')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
$rec_id = mysql_insert_id();
and for ingredient
$ingredient = $_POST['ingredient'];
$amount = $_POST['amount'];
$integer = 0;
while (count($ingredient)>$integer) {
if (($ingredient[$integer] <> "") && ($amount[$integer] <> "")){
$sql = "INSERT INTO `cafe`.`ingredients` (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";
mysql_query($sql);
echo $sql."";
}
else{
echo "ingredient number ".($integer+1)." is missing values and cannot be inserted.";
}
$integer = ($integer + 1);
}
when i echo the queries the out put is nsert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', 'demo recipe','no overview','meal','10/12/10 : 13:02:33','http://www.localhost/cafe/pics/demo.gif')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient one', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient two', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient three', '3gm', '29')
but when i see the mysql table or retriew data from ingredient there is no data in ingredient.
You have an extra , after rec_id.
Remove it, so it looks like
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id) VALUES ('', 'ingredient one', '3gm', '29')
And you will be OK
There seems to be a syntax error in your code:
if (($ingredient[$integer] "") && ($amount[$integer] ""))
^^ ^^
Looks like you are missing a comparison operator.
You might want to verify if you are using a BEGIN call and not committing after INSERT. You can refer to http://www.devarticles.com/c/a/MySQL/Using-Transactions-with-MySQL-4.0-and-PHP/
in that scenario.
When insert doesnt throw exceptions and doesnt insert data there are I think a couple of options
1) you use transaction somewhere and rollback it
2) your select query is bad and data is there, but you just dont select it
remove cafe from the query
$sql = "INSERT INTO ingredients (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";

Categories