We have some array of values that want to insert them to the database.
for example:
$first_Names = array("Bob","John","Paolo","Jack", "Alex");
$last_Names = array("Charlton", "Smith", "Maldini", "Rooney", "anotherlastname");
Now I want to insert them to database
$sql = "INSERT INTO people(fname, lname) VALUES(:fname, :lname)";
Can I bind array directly without using foreach command and insert them one by one items?
Related
Using PDO in PHP, 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 in PHP if I want to be able to bind my values to a statement like I do in single statement:
$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
"firstname"=>$firstName,
"lastName"=>$lastName));
So my question is: Is there any way to bind in a multi-insert statement? Something like:
INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));
In theory, it might sound like a single statement is more efficient because you avoid making multiple calls to MySQL server, but the reality is that this a micro-optimization and you are overcomplicating your code for barely any benefit.
The cool thing about prepared statements is that it is prepared once and can be executed multiple times. This already saves you parsing the SQL statement multiple times. Simply prepare a statement outside of a loop and then execute it inside a loop.
$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO table (firstName, lastName) VALUES(?,?)');
foreach ($names as $name) {
$stmt->execute($name);
}
If you wrap the whole thing in a transaction as Your Common Sense suggested in the comments then there is no noticeable difference in performance compared to one big statement.
$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO people (firstName, lastName) VALUES(?,?)');
$pdo->beginTransaction();
foreach ($names as $name) {
$stmt->execute($name);
}
$pdo->commit();
Just create your query text wtih ? placeholders as:
INSERT INTO table (firstName, lastName) VALUES (?, ?),(?, ?),(?, ?)
And execute it. Sample code can be:
$data = ['Joe', 'Smith','Fred','Sampson','Lisa','Pearce'];
$placeholders = ['(?, ?)', '(?, ?)', '(?, ?)']; // but you should define this data according to your data
$query = 'INSERT INTO table (firstName, lastName) VALUES ' . implode(',', $placeholders);
$stmt = $dbh->prepare($query);
$stmt->execute($data);
Using PDO in PHP, 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 in PHP if I want to be able to bind my values to a statement like I do in single statement:
$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
"firstname"=>$firstName,
"lastName"=>$lastName));
So my question is: Is there any way to bind in a multi-insert statement? Something like:
INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));
In theory, it might sound like a single statement is more efficient because you avoid making multiple calls to MySQL server, but the reality is that this a micro-optimization and you are overcomplicating your code for barely any benefit.
The cool thing about prepared statements is that it is prepared once and can be executed multiple times. This already saves you parsing the SQL statement multiple times. Simply prepare a statement outside of a loop and then execute it inside a loop.
$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO table (firstName, lastName) VALUES(?,?)');
foreach ($names as $name) {
$stmt->execute($name);
}
If you wrap the whole thing in a transaction as Your Common Sense suggested in the comments then there is no noticeable difference in performance compared to one big statement.
$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO people (firstName, lastName) VALUES(?,?)');
$pdo->beginTransaction();
foreach ($names as $name) {
$stmt->execute($name);
}
$pdo->commit();
Just create your query text wtih ? placeholders as:
INSERT INTO table (firstName, lastName) VALUES (?, ?),(?, ?),(?, ?)
And execute it. Sample code can be:
$data = ['Joe', 'Smith','Fred','Sampson','Lisa','Pearce'];
$placeholders = ['(?, ?)', '(?, ?)', '(?, ?)']; // but you should define this data according to your data
$query = 'INSERT INTO table (firstName, lastName) VALUES ' . implode(',', $placeholders);
$stmt = $dbh->prepare($query);
$stmt->execute($data);
Using PDO in PHP, 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 in PHP if I want to be able to bind my values to a statement like I do in single statement:
$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
"firstname"=>$firstName,
"lastName"=>$lastName));
So my question is: Is there any way to bind in a multi-insert statement? Something like:
INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));
In theory, it might sound like a single statement is more efficient because you avoid making multiple calls to MySQL server, but the reality is that this a micro-optimization and you are overcomplicating your code for barely any benefit.
The cool thing about prepared statements is that it is prepared once and can be executed multiple times. This already saves you parsing the SQL statement multiple times. Simply prepare a statement outside of a loop and then execute it inside a loop.
$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO table (firstName, lastName) VALUES(?,?)');
foreach ($names as $name) {
$stmt->execute($name);
}
If you wrap the whole thing in a transaction as Your Common Sense suggested in the comments then there is no noticeable difference in performance compared to one big statement.
$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO people (firstName, lastName) VALUES(?,?)');
$pdo->beginTransaction();
foreach ($names as $name) {
$stmt->execute($name);
}
$pdo->commit();
Just create your query text wtih ? placeholders as:
INSERT INTO table (firstName, lastName) VALUES (?, ?),(?, ?),(?, ?)
And execute it. Sample code can be:
$data = ['Joe', 'Smith','Fred','Sampson','Lisa','Pearce'];
$placeholders = ['(?, ?)', '(?, ?)', '(?, ?)']; // but you should define this data according to your data
$query = 'INSERT INTO table (firstName, lastName) VALUES ' . implode(',', $placeholders);
$stmt = $dbh->prepare($query);
$stmt->execute($data);
I am trying to insert multiple rows into a table based on the array...with each $value being each of the comma separated values.
I know this is NOT the best way or even correct way to do this - just trying to get some guidance on how to achieve this the right way.
$someArray=array(96,97,98,99,100,101,103,105);
foreach($someArray as $value){
$sql = "INSERT INTO bid_package(user_company) VALUES('".$value."');";
echo $sql;
echo "<br />";
INSERT INTO bid_package(user_company) VALUES('96');
INSERT INTO bid_package(user_company) VALUES('97');
INSERT INTO bid_package(user_company) VALUES('98');
INSERT INTO bid_package(user_company) VALUES('99');
INSERT INTO bid_package(user_company) VALUES('100');
INSERT INTO bid_package(user_company) VALUES('101');
INSERT INTO bid_package(user_company) VALUES('103');
INSERT INTO bid_package(user_company) VALUES('105');
You can put multiple lists of values in a single INSERT:
$values = implode(', ', array_map(function($val) {
return "($val)";
}, $someArray));
$sql = "INSERT INTO bid_package (user_company) VALUES $values;";
This will create a query that looks like this:
INSERT INTO bid_package (user_company) VALUES (96), (97), (98), (99), (100), (101), (103), (105);
If you were using PDO, it would be better to use a prepared statement, to prevent SQL-injection.
$values = implode(', ', array_fill(0, count($someArray), "(?)"))
$sql = "INSERT INTO bid_package (user_company) VALUES $values;"
$stmt = $conn->prepare($sql);
$stmt->execute($someArray);
First, you should be using prepared statements instead of inserting the variable directly into the query. Here is one way of doing what you are attempting.
$mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb'); // your mysqli handle
$stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)"); // prepare your query
//bind value as a reference
$stmt->bind_param('s', $val);
//define values
$someArray=array(96,97,98,99,100,101,103,105);
//loop through values
foreach($someArray as $val) {
//execute statement
$stmt->execute();
}
If you are ever passing data to a query, you should use prepared statements.
I am entering objects from an array into a database.
I have an array called $graphObject
I am looping through the array like this,
foreach($graphObject['tagged_places']->data as $data) {
}
Then I want to take each one of these values and enter them in to the mysql DB with PDO
$data->id
$data->created_time
$data->place->id
$data->place->location->latitude
$data->place->location->longitude
$data->place->name
I am confused on how to write this loop to enter each one of these fields foreach time a new field exist.
Assuming the DB connection is open and the fields in the DB are named
id created_time place_id latitude longitude name
How would I write this with PDO?
What you probably want to do is to build your insert in a loop and then simply execute a single insert statement. So something like this:
$sql = <<<EOT
INSERT INTO table (
`id`,
`created_time`,
`place_id`,
`latitude`,
`longitude`,
`name`)
VALUES
EOT;
foreach($graphObject['tagged_places']->data as $data) {
// add values into string you can remove single quotes if not needed
// (i.e. for numeric data types)
$values = <<<EOT
(
'{$data->id}',
'{$data->created_time}',
'{$data->place->id}',
'{$data->place->location->latitude}',
'{$data->place->location->longitude}',
'{$data->place->name}'
),
EOT;
$sql .= $values;
}
$sql = rtrim(',', $sql);
// execute query using $sql
// assume you have properly instantiated PDO object in $pdo
$result = $pdo->query($sql);
if (false === $result) {
// something went wrong, so log an error
// this assumes you have not configured PDO to throw exceptions
error_log(var_export($pdo->errorInfo(), true));
} else {
// continue doing whatever you want to do
}
Create a prepared statement:
$stmt = $db->prepare('
INSERT INTO table
(id, created_time, place_id, latitude, longitude, name)
VALUES
(?, ?, ?, ?, ?, ?)
');
Execute it on each loop
foreach($graphObject['tagged_places']->data as $data) {
$stmt->execute(array(
$data->id,
$data->created_time,
$data->place->id,
$data->place->location->latitude,
$data->place->location->longitude,
$data->place->name
));
}