Loop an MySQL query in PHP with DBH - php

everbody.
I have a array I want to store in my database. Each element in each row. So I created a loop with a query using DBH. As normal queries (with no loop) go though with no problem, the query in the loop does not work. How should I correct my code?
for($i=0;$i<$count($array);$i++)
{
$stmt = $dbh->prepare("INSERT INTO table (column1, column2) VALUES (:value1, :value2)");
$stmt->bindValue(':value1', $value1[$i]);
$stmt->bindValue(':value2', $value2[$i]);
$stmt->execute();
}
Even this variant doesnt work
for($i=0;$i<$count($array);$i++)
{
$stmt[$i] = $dbh->prepare("INSERT INTO table (column1, column2) VALUES (:value1, :value2)");
$stmt[$i]->bindValue(':value1', $value1[$i]);
$stmt[$i]->bindValue(':value2', $value2[$i]);
$stmt[$i]->execute();
}

I have fixed the problem by building the query in one loop and executing it outside the loop
$query = "";
for($i=0;$i<$count;$i++)
{
$query .= "INSERT INTO `table` (`column1`, `column2`) VALUES ('".$velue1[$i]."', '".$value2[$i]."'); ";
}
rtrim($query, "; ");
$stmt = $dbh->prepare($query);
$stmt->execute();

Related

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

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.

$mysqli->prepare with SQL Transactions

I am pretty new to SQL Transactions and tried to execute following statement which did unfortunately not work...
$stmt = $mysqli->prepare("
BEGIN;
INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES ("'.$groupName.'","'.$groupDesc.'","'.$user_id.'");
INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), "'.$username.'");
COMMIT;
") or trigger_error($mysqli->error, E_USER_ERROR);
$stmt->execute();
$stmt->close();
Is this even possible what I am trying here or is it completely wrong?
I appreciate every response, thank you!
You are using prepare() wrong way. There is absolutely no point in using prepare() if you are adding variables directly in the query.
This is how your queries have to be executed:
$mysqli->query("BEGIN");
$sql = "INSERT INTO groups (group_name, group_desc, user_id_fk) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssi",$groupName,$groupDesc,$user_id);
$stmt->execute();
$sql = "INSERT INTO group_users (group_id_fk, user_id_fk) VALUES (LAST_INSERT_ID(), ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s",$username);
$stmt->execute();
$mysqli->query("COMMIT");

Simple object sqli insert

Hello I'd like to insert all from $_SESSION into rows $key with value $value
so something like foreach ($_SESSION as $key => $value) {}
Imlooking at:Best way to INSERT many values in mysqli?
name of rows in mysqli is same as names of given $key .I need to insert each $value in its $key (row)
Code:
$query = "INSERT INTO testtable VALUES (?)";
$stmt = $dbc->prepare($query);
$stmt->bind_param("s", $key);
$mysqli->query("START TRANSACTION");
foreach ($_SESSION as $key => $value) {
$stmt->execute();
}
$stmt->close();
$mysqli->query("COMMIT");
Your query has a syntax error, which you never bothered checking for:
$query = "INSERT INTO testtable podatki VALUES (?)";
^^^^^^^^^^^^^^^^^
If that's really the table name, then it should be quoted with backticks:
$query = "INSERT INTO `testtable podatki` VALUES (?)";
^-----------------^
if podatki is a field name, then it should be
$query = "INSERT INTO testtable (podatki) VALUES (?)";
^-------^
And also never assume that a DB operation succeeded. ALWAYS check for errors:
$stmt = $dbc->prepare($query);
if (!$stmt) {
die(mysqli_error($dbc));
}
The error is saying that you are trying to call a member function, namely bind_param(), on a non-object.
That means that this line:
$stmt = $dbc->prepare($query);
is not succeeding,
and thus you have an incorrect return value that is set as the value of $stmt
so when you try to call bind_param it fails because $stmt is not the type of object that it was expecting.

Insert into 2 tables from 1 form. Mysql Transaction?

The user will create an article and submit an image with it.
+The article will go to the articles table.
+The image will go to images table (so that it can be used in other areas of the site).
It has been suggested I use TRANSACTIONS but I am getting errors.
$sql ='BEGIN INSERT INTO articles(article_title, article_text, article_date)
VALUES (?, ?, NOW())
INSERT INTO images(article_id, image_caption)
VALUES(LAST_INSERT_ID(),?);
COMMIT';
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('sss', $_POST['article_name'], $_POST['description'], $_POST['image_caption']);
$OK = $stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
$stmt->free_result();
} else{
echo "Failure- article not uploaded";
}
$mysqli->query("START TRANSACTION");
$stmt = $mysqli->prepare('INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW())');
$stmt->bind_param('ss', $_POST['article_name'], $_POST['description']);
$stmt->execute();
$stmt = $mysqli->prepare('INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?)');
$stmt->bind_param('s', $_POST['image_caption']);
$stmt->execute();
$stmt->close();
$mysqli->query("COMMIT");
It looks like you are using PDO (nice!). With PDO, you can get your transactions in an easy way with beginTransaction() and commit()
Your code would look like:
$pdo->beginTransaction();
// .. fire your 'normal' queries.
// .. and yet some more queries
$pdo->commit();
Then, I'd personally write separate INSERT queries in just two separate statements. More readable in my opinion.
Example:
$pdo->beginTransaction();
$first = $pdo->prepare('INSERT INTO table (field, otherField) VALUES(?,?)');
$second = $pdo->prepare('INSERT INTO table (field, otherField) VALUES(?,?)');
$first->execute(array( .. your data (values) .. ));
$second->execute(array( .. your data (values) .. ));
$pdo->commit();
$sql ='START TRANSACTION;
INSERT INTO articles (article_id,article_title, article_text, article_date) VALUES (NULL,?, ?, NOW());
INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?);
COMMIT;';

Categories