This question already has answers here:
Insert multiple rows with PDO prepared statements
(4 answers)
Closed 8 years ago.
Ok so i need to insert multiple rows into a database using MySql from one form, each row is a result. The was i started doing it is the following:
INSERT INTO results (1,2,3,4,5,6,7) VALUES (1,2,3,4,5,6,7), (8,9,10,11,12,13,14)
And so on, my question is:
I don't know how many rows of results a user will want to insert ( a maximum of 15 will apply). Is their a more practical way of achieving the same result? Or am I better off sticking to the way i originally planned?
1°) Use prepared statement (like in Java):
(For safe code, always use prepared statement and avoid generate SQL)
$stmt = $db->stmt_init();
$stmt->prepare("INSERT INTO foo_table (id, firstname, lastname) VALUES(?, ?, ?)");
foreach($myarray as $row)
{
$stmt->bind_param('iss', $row['id'], $row['firstname'], $row['lastname']);
$stmt->execute();
}
$stmt->close();
To understant "iss" param in bind_param: http://uk3.php.net/manual/fr/mysqli-stmt.bind-param.php
2°) Generate batch insert:
Batch inserts with PHP
Related
This question already has answers here:
Importing CSV data using PHP/MySQL
(6 answers)
How to insert multiple rows from array using CodeIgniter framework?
(13 answers)
Closed 3 years ago.
I have a json file and i want to insert all data to my database.
First i am trying to get contents from json file and store in array. It takes 20 seconds.
$strJsonFileContents = file_get_contents('C:\books.json');
$array = json_decode($strJsonFileContents);
After that i prepare the insert query
$query = $db->prepare("INSERT INTO product SET
webID = ?,
name = ?,
subtitle = ?,
title = ?,
description = ?,
ISBN = ?
.
.
.
");
I create a foreach loop and execute insert query.
foreach($array->Books as $book){
$insert = $query->execute(array(
$book->p2,
$book->p3,
$book->p4
.
.
.
));
This foreach loops has 300.000 loop. It takes huge time to insert. - I didn't see finish, it made 40,000 additions in about 10 minutes.
What should I do to reduce this time to seconds? It is not a big problem for me to have 20 seconds to read from the file but inserting time it is a huge problem.
One way to reduce this is to create one query using the following syntax:
INSERT INTO `product` (`webID`, `name`, `subtitle`, `title`, `description`, `ISBN`)
VALUES (?,?,?,?,?,?),(?,?,?,?,?,?) .... // and so on
Using the PHP to assemble the VALUES portion of the query as you can have multiple sets of these. Then run the query ONE time.
Regardless of how you do this, it will take some time to prepare the query and then execute it. Inserting that many rows at once is not trivial.
This question already has answers here:
How do I get the last inserted ID of a MySQL table in PHP?
(16 answers)
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I have a MYSQL database query nested in a foreach statement like this:
foreach ($_POST['articles'] as $article => $number) {
$sql_update2 = "INSERT INTO testmerrill.Device_Article_Connection (device_id, article_id)
VALUES ((MAX (device_id) FROM testmerrill.Devices),'{$_POST['articles'][$article]}))'";
query_db1($sql_update2);
}
The above query runs after this one:
$sql_update1 = "INSERT INTO testmerrill.Devices (device_name, device_manufacturer)
VALUES ('{$device_name}', '{$device_manufacturer}')";
query_db1($sql_update1);
This page is the create page of a CRUD program I am writing. I have two tables I am working with here: Devices and Device_Article_Connection. What I am trying to do is insert into my Device_Article_Connection table multiple select statement options the user posted on submit, calling a query for as many options the user chose to include as associated with a new 'device'. I know my current solution is probably not a very elegent way to do it, but thats where I'm at at the moment. The difficulty is that I do not know the id of the new device the user just created, which I need in order to associate it with the articles the user chose to associate with it. I am trying to find the device id using the MAX function (because the last id the user just added should be the largest), but I can't seem to get that to work, there is some syntax error that I have not been able to pinpoint.
I am thankful for any suggestions.
If you use mysqli for a database connection, you could use insert_id to solve this problem:
$conn = new mysqli($server, $user, $pass, $db);
$q = $conn->prepare("INSERT INTO testmerrill.Devices (device_name, device_manufacturer) VALUES (?, ?)"); // Prepare the query
$q->bind_param("ss", $device_name, $device_manufacturer); // Bind variables to prevent SQL injection
$q->execute();
$last_id = $q->insert_id; //Represents the last inserted id
This question already has answers here:
PHP MySQLi Multiple Inserts
(3 answers)
Closed 9 years ago.
I'm trying to figure out how to properly achieve multiple row inserts along the format of
insert to tbl values (?,?,?), (?,?,?), (?,?,?);
The mysqli_bind_param doc is pretty clear on how to accomplish this for a single row.
From the docs their example looks like:
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
However I have an multi-dimensional array where each inner element represents a value set, or row, to be inserted.
Well, you have 2 choices
Use the very prepared statement approach to do multiple inserts using once prepared query. Wrapped in a transaction they have to be blazingly fast
Create a dynamical call to bind_param which is going to be a pain, an unexpected pain. For some reason mysqli makes dynamical binding overcomplicated.
You will need to merge your array into single one, then create a second array for the references and then call call_user_func_array() for this latter approach. Dunno if it worth the mess.
This question already has answers here:
PHP MySQLi Multiple Inserts
(3 answers)
Closed 3 years ago.
Hoping someone can give me some insight here.
When having to insert multiple rows into a table at once, I've used sql that looks something like this:
INSERT INTO some_names (firstName, lastName) VALUES ('Joe', 'Smith'),('Fred','Sampson'),('Lisa','Pearce')
As you can see I'm inserting three rows with one statement. The reason I do this is that I believe it is more efficient than executing three distinct statements to insert the rows.
So my question is this: how do I do this if I want to be able to bind my values to a statement? Unfortunately I've been looking all over the web and I can only find example of single statements in the form of:
$stmt = $mysqli->prepare("INSERT INTO some_names (firstName, lastName) VALUES (?, ?)");
$stmt->bind_param('ss', $firstName, $lastName);
$firstName = "Joe";
$lastName = "Smith";
$stmt->execute();
$firstName = "Fred";
$lastName = "Sampson";
$stmt->execute();
It seems that this would be the equivalent of doing separate INSERT statements and seems to be less efficient.
So my question is: Is there any way to bind in a multi-insert statement? Please educate me here! Thanks
Simple:
$stmt = $mysqli->prepare("INSERT INTO some_names (firstName, lastName) VALUES (?, ?),(?,?),(?,?)")
$stmt->bind_param('ssssss', 'Joe', 'Smith','Fred','Sampson','Lisa','Pearce');
It seems that this would be the equivalent of doing separate INSERT statements and seems to be less efficient.
No, it’s not less efficient – because a statement is prepared only once (to figure out what it is supposed to do), and after that is done only the data is send to the database afterwards.
You are looking at this the wrong way.
You would pretty much never do what you have shown above, it would almost always be done in a loop. And even if you dynamically constructed (?, ?), (?, ?), (?, ?) you would still have to loop to build the query string and bind the data (which would get even more complicated because of MySQLi's ridiculous insistance on by-ref bindings) so it wouldn't gain you anything in terms of work that needs to be done by PHP - you just moved the loop - and it would lose you a lot in terms of readability.
It does have a gain in round trips to the database (assuming you are always inserting more than one row) - but this would only make a meaningful difference when inserting hundreds or thousands or rows, in which case you are most likely performing some kind of import operation, in which case the extra couple of seconds probably don't matter (it won't be e.g. slowing a page load).
This question already has answers here:
Retrieving the last inserted ids for multiple rows
(2 answers)
Closed 9 years ago.
MySQL code is something like:
INSERT INTO table(name, value) VALUES ('name1', 'value1'), ('name2', 'value2'), ('name3', 'value3')
Basically, multiple inserts in the same SQL statement.
How can I get the IDs of the inserted values. I assume mysql_insert_id() combined with the number of inserts isn't safe since someone else might insert something at the same time.
Is there another way?
You either need to insert them one at a time or figure out the id's with a followup query.
INSERT INTO table(primkey, value) VALUES ('pk1', 'val1'), ('pk2', 'val2');
SELECT FROM table id, primkey where primkey in ('pk1', 'pk2');