I'm new to PHP and I'm trying to insert data from a nested array into a database. I'm noticing though that only the last key:value gets put in (seems almost as if everything else before gets overwritten). How do I get a new line of each data so everything gets put in?
$tmpArray = array(array("one" => abc, "two" => def), array("one" => ghi, "two" => jkl));
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Scan through inner loop
foreach ($innerArray as $key => $value) {
if ($key === 'one') {
$sql = "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value')";
}
}
}
For simplicty, all I'm trying to do is to get "one" and "abc" put into alpha and beta. Then have another row of the table input "one" and "ghi". But when I run the code, all I get is "one" and "ghi". When I put an echo statement though, all the correct stuff gets printed. Just don't understand why they aren't getting input into my tables.
What am I doing wrong? Thanks!
$sql = "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value')";
This line overwrites the contents of the variable $sql every time it is called. You need to concatenate your strings together instead:
$sql = '';
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Scan through inner loop
foreach ($innerArray as $key => $value) {
if ($key === 'one') {
$sql .= "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value'); ";
}
}
}
Still better, as suggested in a comment, would be to simply execute the query directly rather than store it in a variable. Then you don't have to concatenate the strings together, nor do you have to enable multiple statements in a single MSQLI call.
Related
I have a dynamic HTML form with three fields (item, number, cost). Users can add as many rows as they need. Because of this, I have set the fields names as item[], number[], cost[] in order to loop through the post and insert the values in the DB.
I have verified that the values are posted correctly up correctly through vardump, and I have checked that the following loop is picking up the values (both key and value) through printr. (and also simply echoing $value1).
foreach ($_POST as $field => $value) {
foreach($value as $field1 => $value1){
echo $field . ':' . $value1 . '</br>' ;
}
};
However, if I try insert passing the values to execute, nothing happens (no data is inserted and I get no error message).
if($_POST['submit']){
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare('INSERT INTO invoice (item, number, cost) VALUES (?,?,?);');
foreach ($_POST as $item => $value) {
foreach($value as $item1 => $value1){
$stmt->execute($value1);
}
}
$pdo->commit();
}
catch (Exception $e){
$pdo->rollback();
throw $e;
}
}
I know that $value1 holds the correct values, but they are not being inserted. Can anyone help?
I have tried:
https://phpdelusions.net/pdo_examples/insert#multiple
PDO insert statement with loop through $_POST array
PDO insert array values Insert multiple rows using form and PDO
Need php pdo implode arrays and insert multiple rows in mysql
As your $_POST array contains columns you need to get values from the corresponding cells, i.e. for the first row you need items[0], number[0] and cell[0] and so on. So iterate over the first column, get the index and use that index for the other two
foreach ($_POST['item'] as $i => $item) {
$stmt->execute([$item, $_POST['number'][$i], $_POST['cost'][$i]]);
}
I'm not sure how to go about this. I have a nested foreach that I'm attempting to build an insert query from.
preg_match_all('/...../', $text, $matches);
foreach ($foo[0] as $bar){
$item1 = $bar
preg_match_all('/..'/, $bar, $result){
foreach($result[0] as $link){
something here
}
$insertstuff = "insert ignore into table (field1, field1) values (value1, value2)..etc
mysql_query($insertstuff, $con);
}
So here is my question. There will be anywhere from 0 - 10 links returned in the nested foreach. How do I build the query to take those links and insert them into the respective column, ie link1, link2 --> link10. This is just a barebones example, I just am not sure how to structure the query to take into account the unknown number of things to insert.
To update: I have it working but i'm not sure if it's the most efficient.
$i=1;
foreach ($result[0] as $link) {
if ($i=1)
{$link1 = $link;}
elseif ($i=2)
{$link2 = $link;}
elseif ($i=3)
{$link3 = $link;}
etc down to 10.
$i++;
}
Thank you
This is a snippet of my code. I essentially I have a new array I want to insert into tablename, but before I do that I validate the new stat figures against the old ones, confirm they are numeric and insert into a new row.
I realise what I have done, the mysql_query is inside the foreach loop, it inserts 5 rows all the same. I want it to only insert 1 new row.
How Do I take the mysql_query outside the loop yet keep the validation that the foreach loop provides before attempting to insert a new row?
foreach ($statnumber as $element) {
if ($statnumber != $LastWeeksStats && is_numeric($element)) {
mysql_query("INSERT INTO tablename (idproducts, stat1, stat2, stat3, stat4, stat5, superstat1) VALUES('8', '$statnumber[0]', '$statnumber[1]', '$statnumber[2]', '$statnumber[3]', '$statnumber[4]', '$statnumber[5]')") or die(mysql_error());
} else {
echo "'{$element}' is NOT numeric or results same as last week", PHP_EOL;
}}
mysql_close();
I would remove the elements that fail the check from the array then have the mysql statement outside the loop at the end. Use unset but you have to keep track of what keys to unset like this:
foreach ($statnumber as $key => $element) {
if($statnumber != $LastWeeksStats && is_numeric($element)) {
//do nothing because it is valid
} else {
//remove that element from the array
unset($statnumber[$key]);
echo "'{$element}' is NOT numeric or results same as last week", PHP_EOL;
}
}
//now only valid data is in the array and you can use a mysql query
You will have to update the mysql query based on how many elements are actually in the array at the end like so:
foreach($statnumber as $key => $element) {
$keys[] = "stat$key";
$elements[] = "'$element'";
}
$keystring = implode(",",$keys);
$elementstring = implode(",",$elements);
mysql_query("INSERT INTO tablename (idproducts, $keystring, superstat1) VALUES('8', $elementstring)") or die(mysql_error());
I am imploding data inside of an array, called the following:
["Levels_SanctionLevel_array"]=>
string(14) "IR01,IR02,IR03"
I need to explode this data and input each value as a row inside of mysql. Such as
pri_id value
---------------
01 IR01
02 IR02
03 IR04
Now where I am getting stuck is this:
The array listed above could have 1 value, 3 values (right now I am showing three values) or 5 values, and I dont want to input NULL values inside of my database.
Appreciate any guidance anyone can share...
$data = explode(',',$your_string);
foreach ($data AS $value) {
// INSERT INTO DB
}
A simple loop works correctly, but has the drawback of making multiple queries to the database:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
foreach ($vals AS $value) {
// insert into database
}
As DB operations are a more significant bottleneck than building a query in PHP, I would opt to generate the SQL code for a single query as follows:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
$query = 'INSERT INTO my_data VALUES ';
foreach ($vals as $value) {
$query .= "('', '".$value."'),";
}
$query = rtrim($query, ',');
// insert into database
Why don't you use an iterator over the array to construct the sql query? That way you will only insert as many elements as you have in the array.
Like the answer above. I think we were answering at the same time.
Supposing your major array is $data:
foreach ($data as $values)
{
$value = explode(",", $values);
foreach ($value as $v)
{
$sql = "INSERT INTO table(value) VALUES('$v')";
}
}
what is the optimal way for me to insert and array of 1000 lines and 10 columns each into a mysql table below is how i display it so it would be a similar construct but i need some directions
foreach ($stack as $val) {
print "<tr>\n";
foreach ($val as $no) {
print " <td>$no</td>\n";}
print "</tr>\n";
}
You can insert multiple rows with a single insert as follows :
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
look at implode() to create the values string from your array
Better way to insert thousands of data into DB is to use implode function implode
i'm guessing u got something like this
$stack = array("man1" => array("name"=>"ik", "class"=>"highskl", "age"=> "12"),"man1" => array("name"=>"ijk", "class"=>"higkl", "age"=> "13"));
and you want to insert them into a table, try and use the table fields as index for the inner arrays then adjust the code to look like this
foreach ($stack as $entry => $value) {
$query = "INSERT INTO table set ";
foreach ($value as $key => $val) {
$query .= $key ."= ".$val.",";}
//use a string function to remove the last comma
$result = mysql_query($query) or die("Error in Query ".$entry." ",mysql_error());
//this helps to track error..
}