mysqli insert multiple rows from a loop - php

I am trying to insert multiple rows based on a loop.
This code inserts the first item from the loop only, then ignores the rest of the loop
I know the loop is counting correctly as echo'ing out the values outputs ok
$i = 1;
while ($i <= $count){
foreach($html->find('.markuptag a') as $mystring){
if(preg_match_all("|<a.*(?=href=\"([^\"]*)\")[^>]*>([^<]*)</a>|i", $mystring, $matches)){
$a = $matches[2][0];
}
$query = "INSERT INTO mytable (`firstname`, `lastname`, `var_a`) VALUES ('$fistname', '$lastname', '$a')";
$mysqli->query($query);//<< is there a better way?
}
$i++;
}

Build an array of the rows to insert, then insert them all at once. Something like this:
$arr = []; // array() in PHP 5.3 and older
foreach(...) {
...
$arr[] = "('$fistname', '$lastname', '$a')";
}
$mysqli->query("INSERT INTO mytable (`firstname`, `lastname`, `var_a`) VALUES "
.implode(",",$arr));

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

how to insert different multiple arrays in mysql using php

I have a form something like below:
<input name="first_name[]" type="text">
<input name="last_name[]" type="text">
<input name="email[]" type="email">
I am using while loop to print/echo number of groups of above form fields it required.
There will be multiple data in it, i'm not understanding how use insert query to insert data in mysql table using php.
First, you will need to know how many records you are trying to insert. I used first_name for this, but you could use any of them. (I am assuming since these are grouped together that you will always have the same number of first_name, last_name, and email.):
$count = count($_POST['first_name']);
After you know that, you can build an SQL statement that will insert all of the records in one query:
$sql = "INSERT INTO people (first_name, last_name, email) VALUES ";
$sql .= implode(', ', array_fill(0, $count, '(?, ?, ?)'));
The second line (implode...) will create sets of placeholders in the statement for each record you are trying to insert. (The three question marks represent the three columns you are inserting.) For example, if you had two field groups, the statement would look like:
INSERT INTO people (first_name, last_name, email) VALUES (?, ?, ?), (?, ?, ?)
After you have created the SQL string, you can create a new PDO connection and use that connection to create a prepared statement using your SQL.
$pdo = new PDO($dsn, $user, $password);
$statement = $pdo->prepare($sql);
Next you need to bind your values to the prepared statement. There are various different ways to do this. Here is one example:
// Create a multidimensional array using each of the fields from your field groups
$columns = array($_POST['first_name'], $_POST['last_name'], $_POST['email']);
$index = 1; // This is the index of the placeholder in the prepared statement
for ($i=0; $i < $count; $i++) { // This will loop as many times as you have field groups
$row = array_column($columns, $i);
// using array_column will pull everything from the $i index of each of the sub-arrays
// e.g. first_name[$i], last_name[$i], email[$i]
foreach ($row as $value) {
// bind the value and increment the index
$statement->bindValue($index, $value);
$index++;
}
}
After you have bound all the parameters, you can execute the prepared statement:
$statement->execute();
You can try something like this (you can find comments in the code):
if (isset($_POST['yourSubmitButton']) && isset($_POST['first_name'])) {
try {
$conn = new PDO("mysql:host=localhost;dbname=mysql", 'db_username', 'db_password');
}
catch(PDOException $e) {
echo $e->getMessage();
die();
}
$sql = 'INSERT INTO your_table (first_name, last_name, email) VALUES ';
$sql_append = array(); //Here we have the placeholder to be inserted
$binds = array(); //Here he have the values for the placeholders
for($i = 0; $i < count($_POST['first_name']); $i++) {
if (!( isset($_POST['first_name'][$i]) && isset($_POST['last_name'][$i]) && isset($_POST['email'][$i]) )) {
//We need all the values to be valid
continue;
}
//Add the placeholders and bind values
$sql_append[] = '(first_name = :first_name'.$i.', last_name = :last_name'.$i.', email = :email'.$i.')';
$binds[':first_name'.$i] = $_POST['first_name'][$i];
$binds[':last_name'.$i] = $_POST['last_name'][$i];
$binds[':email'.$i] = $_POST['email'][$i];
}
//Implode and add to the query and then execute
$sql = $sql.implode(', ', $sql_append).';';
$stmt = $conn->prepare($sql);
$stmt->execute($binds);
}
If you have 2 rows $sql will have:
echo $sql;
Result:
INSERT INTO your_table (first_name, last_name, email) VALUES (first_name = :first_name0, last_name = :last_name0, email = :email0), (first_name = :first_name1, last_name = :last_name1, email = :email1);

Insert different values in array in MySQL in the same columns with just 1 insert

How can I do this:
for ($i=0; $i<$number; $i++)
{
mysql_query("INSERT INTO blah (foo, bar) VALUES (".$array[$i].", 1)");
}
With just one INSERT?
Is it possible?
PS: I know mysql_query is deprecated.
You can pass multiple VALUES in INSERT statement like:
INSERT INTO blah(foo, bar)
VALUES (...), (...), (...), (...),...
You can do:
$stmt = "";
for ($i = 0; $i < $number; $i++) {
$stmt .= "INSERT INTO blah (foo, bar) VALUES (" . $array[$i] . ", 1);";
}
//deprecated: mysql_multi_query($stmt);
mysqli_multi_query($stmt);

Insert MySQL not working with var and insert empty row

I tried for long time understand what got wrong in this code:
I have two arrays that I want to put in the DB but the array can be changed any time. So it need to work dynamically.
All I get is an empty row without any data - but as string it work fine.
If I write the output string of query instead it works, but this way not:
$fields = $values = array();
$j = 0;
while ($j < mysql_num_fields($query)) {
$namee = mysql_fetch_field($query, $j)->name;
if(isset($AutoFill[$namee])){
if($AutoFill[$namee] == '?')
$values[] = "'".mysql_real_escape_string("dopd")."'";//$_POST[$namee]
else
$values[] = "'".mysql_real_escape_string($AutoFill[$namee])."'";
$fields[] = "$namee";
}
$j++;
}
$fields = implode(",", $fields);
$values = implode(",", $values);
// not working
mysql_query("INSERT INTO ".$table_name." (".$fields.") VALUES (".$values.")");
// "INSERT INTO ".$table_name." (".$fields.") VALUES (".$values.")" => tostring working:
mysql_query("INSERT INTO _users (user_name,display_name,password,email,activation_token,last_activation_request,lost_password_request,active,title,sign_up_stamp,last_sign_in_stamp) VALUES ('dopd','dopd','dopd','dopd','dopd','1409863484','0','dopd','New Member','1409863484','0')");
This will not work because you cannot pass an array into a query.
mysql_query("INSERT INTO ".$table_name." (".$fields.") VALUES (".$values.")");
Try this instead:
mysql_query( "INSERT INTO ".$table_name." ('" . implode("','", $fields) . "') VALUES ('" . implode("','", $values) . "');" );
This will create a string out of your array that will pass into the SQL statement correctly. Do your implode within the query statement rather than above. Also, you were not wrapping the values in quotes individually, so you were getting one long string of values (ie: '1,2,3') instead of individually quoted values (ie: '1','2','3').
The solution for this was that the $query was not declered properly in the right place og scope.
The code work's great on any king and length of information from user.
thank you all - best weekend.

Weird insert behavior with mysql and codeginiter

I have a fairly simple insert statement
<...>
if (!empty($attributes)) {
$sql = 'INSERT INTO `part_attrs` (`part_id`, `attr`, `type`, `list_order`) VALUES (?, ?, ?, ?)';
foreach($attributes as $key => $attribute) {
$this->db->query($sql, array($partid, $attribute[0], $attribute[1], $key));
$attrid = $this->db->insert_id();
echo $attrid.'<br />';
if (strlen($attribute[2]) > 0) {
$values = explode(',', $attribute[2]);
$sql = 'INSERT INTO `attr_values` (`attr_id`, `field_values`) VALUES (?, ?)';
foreach ($values as $value) {
$this->db->query($sql, array($attrid, trim($value)));
}
}
}
}
<...>
The odd thing is only one or two of the rows are being inserted. I put that echo line in to see the row id's it was returning for each insert since I'm not getting any errors. If for example I insert three items it will return something like 18, 124, 128. Where the 18 id is the next and expected id so this row gets inserted and then the rest don't. Any ideas what might be wrong?
You are changing the value of $sql inside your second if statement. 124 and 128 is attributes from the attr_values table. Consider using another variable name inside your if statement, or move the first assignment to $sql inside the foreach loop (move it down one line).

Categories