How do i implement 'INSERT' using PHP PDO - php

Using PHP's PDO and prepared statements, how do I implement the following?
$sql = 'insert into $tablename ($var1, $var2, $var3, ...) VALUES (:placeholder1, :placeholder2, ...)';
Thanks.

Here is one way to do it:
$sth = $dbh->prepare('INSERT INTO '.$tablename.' ('.implode(',', array_keys($inserting)).') VALUES ('.str_pad('', count($inserting)*2-1, '?,').')');
$sth->execute(array_values($inserting));
Where $tablename is the name of the table and $inserting is an associative array with keys being the names of the columns and the values of the array being the values to insert.

Related

pdo array getting Array to string conversion error

When I run this code it should store ben in the database but, it says Array in the first_name column and it gives the string to conversion error. How would I get rid of the error?
<?php $data = ['first_name' => 'ben'] ?>
<?php $sql = "INSERT INTO names (first_name) values (?);" ?>
<?php $statement = $pdo->prepare($sql); ?>
<?php $statement->execute([$data]); ?>
PDO has two different ways to bind parameters. The first is positional. In this case, the array you pass to execute() should be an indexed array, with values in the same order that you want them to bind to the question marks:
$sql = "INSERT INTO table (col1, col2) values (?, ?)";
$data = ['value for col1', 'value for col2'];
Note the values must be in the same order that they're going to be used:
$data = ['value for col2', 'value for col1']; // This won't work, wrong order!
The alternative (and in my opinion, superior) method is to use named parameters. Here, you need to use an associative array with a key named the same as your parameter placeholder.
$sql = "INSERT INTO table (col1, col2) values (:col1, :col2)";
$data = ['col1' => 'value for col1', 'col2' => 'value for col2'];
The order of these now does not matter because they're keyed by the array name instead of the position:
$data = ['col2' => 'value for col2', 'col1' => 'value for col1']; // Still good!
Your problem (in addition to the extra array wrap that #Sammitch pointed out) is that you have mixed these two techniques together in an incompatible way -- you're using positional parameters, but have provided an associative array. So, in your case, you either need to use positional parameters and an indexed array:
$data = ['ben'];
$sql = "INSERT INTO names (first_name) values (?);";
$statement = $pdo->prepare($sql);
$statement->execute($data);
Or named parameters and an associative array:
$data = ['first_name' => 'ben'];
$sql = "INSERT INTO names (first_name) values (:first_name);";
$statement = $pdo->prepare($sql);
$statement->execute($data);

How to implement prepared statement in a loop? [duplicate]

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

How to efficiently insert data to mysql using PDO? [duplicate]

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

PDO and binding multiple value sets during insert

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

PHP 'For Each' Insert rows into mysql from array or string

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.

Categories