How to loop through appended inputs inside an array - php

I'm submitting appended inputs through an API. The number of items is different every time. When I submit the form, the input is submitted successfully and an object is returned, but only the last appended input is submitted. How can I run a loop inside of the array shown, or what syntax of loop works here so that I will submit a new item for each appended input? thank you for considering.
<script>
$(document).ready(function(){
$("#new").click(function(){
$("table").append("<tr><td><input type= 'text' name = 'item[]'</td> </tr>");
});
});
</script>
<?php
after a form/table with input name="item[]" my PHP:
if (isset($_POST['submit']))
{
$size = sizeof($_POST['item']);
for ($i = 0; $i < $size; $i++)
{
$product = $_POST['item'][$i];
}
$fields = array(
'customer' => 992058,
'items' => [
[
'name' => $product,
]
]
);
// HERE IS A CURL CALL that POSTS $fields AND RETURNS JSON
?>
the JSON I'd like to see returned might look something like
"items":[{"name":"product1"}][{"name":"product2"}];
instead of what I'm getting which is
"items":[{"name":"product2"}]

Here is what you need to:
if (isset($_POST['submit']))
{
$size = sizeof($_POST['item']);
$products = [];
for ($i = 1; $i < $size; $i++)
{
$products[]['name'] = $_POST['item'][$i];
}
$fields = array(
'customer' => 992058,
'items' => $products
);
The problem with your code that var $product get only the last insert while running through the loop, you need to create an array inside the loop.

Related

How to insert in loop again inside loop then Insert query

$product_id = $request->input("product_id");
$size_id = $request->input("size");
$price = $request->input("price");
$shade_id = $request->input("shade_id");
$arr = array();
if($shade_id){
for($i=0; $i<count($shade_id); $i++){
$shades_id = $shade_id[$i];
if($size_id){
for($j=0; $j<count($size_id); $j++){
/*$insert = DB::table('tbl_product_shade_attributes')
->insertGetId(['product_shade_id' => $shade_id[$i], 'product_id'=> $product_id,'size_id' => 1, 'price'=> 200]);*/
$arr[$j] = [
'product_shade_id' => $shades_id,
'product_id'=> $product_id,
'size_id' => $size_id[$j],
'price'=> $price[$j]
];
}
}
}
}
I'm not pretty sure why it doesn't insert properly data on the database.
My HTML Structure:
MY Database Structure
My output is displaying on the console log
This is my FormData
Please see my AJAX FormData

JSON decode foreach -> only delivery 1 row

my code only delivery 1 row. The first. This JSON contain 3000 rows.
Does anyone know why?
Thanks!
if (!empty($_GET["cuit"])){
$cuit = $_GET["cuit"];
$directorioDocs = 'data/docs/';
$data = file_get_contents("data/data.json");
$proveedores = json_decode($data, true);
$i = 0;
foreach ($proveedores as $proveedor) {
if ($cuit == $proveedor[$i]['cuit']) {
$proveedorArray = array(
"cuit" => $proveedor[$i]['cuit'],
);
}
else {$proveedorArray = array("Data" => "Debe ingresar un cuit");
}
$i = $i + 1;
}
echo json_encode($proveedorArray);
}
else
{
$proveedorArray = array("Data" => "Debe ingresar un cuit");
echo json_encode($proveedorArray);
}
$proveedorArray = array(
"cuit" => $proveedor[$i]['cuit'],
);
Creates a new array each iteration through the loop. You need to append instead:
// assuming each item in the parent array should be another array
$proveedorArray[] = array(
"cuit" => $proveedor[$i]['cuit'],
);
You'll also have to do the same in your else case inside the loop.
I tell you that the solution was found when analyzing the json
I did it with this tool->
https://jsonlint.com/
I'm missing this->
foreach ($proveedores['data'] as $proveedor) {
Also remove the index [0] that was already unnecessary
That was it
Thanks

how i save the data into database that has been created using fetch

This is first picture
]3
This is a second picture when i click the dropdown list it fetch the item and display like a table format.
This is a third picture in this i have done some calculation..
My problem is how to save that table into database because this table has been created in model page...
public function Op_insert($data){
$count = count($data['name']);
for($i = 0; $i<$count; $i++){
$data[] = array(
'Stock' =>$data['Stock'][$i],
'Rate'=>$data['Rate'][$i],
'Amount' =>$data['Value'][$i]
);
}
$this->db->insert_batch('opstock', $data);
}
this is model code..
I think problem with your variable name, you are using same variable for save new data that is $data rename with "$new_data"
public function Op_insert($data){
$count = count($data['name']);
for($i = 0; $i<$count; $i++){
$new_data[] = array(
'Stock' =>$data['Stock'][$i],
'Rate'=>$data['Rate'][$i],
'Amount' =>$data['Value'][$i]
);
}
$this->db->insert_batch('opstock', $new_data);
}

How do i update multiple rows with multiple condition in Code Igniter

I am just learning PHP and using the Codeigniter framework.
I'm using this code in my controller when inserting new data and it's working.
//INSERT MULTI ROWS TABEL harga_inventori
$kode_inventori = $_POST['kode_inventori'];
$result = array();
foreach($_POST['kode_kategori_pelanggan'] AS $key => $val){
$result[] = array(
"kode_kategori_pelanggan" => $_POST['kode_kategori_pelanggan'][$key],
"kode_inventori"=>$kode_inventori,
"harga" => $_POST['harga_jual'][$key],
"diskon" => $_POST['diskon'][$key]
);
}
$res = $this->db->insert_batch('harga_inventori', $result);
redirect("inventori");
But when I'm using the same pattern for the updating function, it's not working at all.
for($i = 0; $i < count($_POST['harga_jual'][$i]); $i++) {
if($_POST['kode_kategori_pelanggan'][$i] != '') {
$res[] = array(
'harga' => $_POST['harga_jual'][$i],
'diskon' => $_POST['diskon'][$i],
);
$this->db->where('kode_inventori',$_POST['kode_inventori']);
$this->db->where('kode_kategori_pelanggan',$_POST['kode_kategori_pelanggan'][$i]);
$this->db->update('harga_inventori',$res);
}
}
redirect("inventori");
I'm trying the update_batch() but I got many errors, so I'm using for loop and updating a single row at a time.
What could be the problem here?
Its only a typo. You should pass the array $res not $data, and change $res[] to $res since it is not needed. You should also check with isset() to prevent errors of undefined:
for($i = 0; $i < count($_POST['harga_jual'][$i]); $i++) {
if(isset($_POST['kode_kategori_pelanggan'][$i])) {
$res = array(
'harga' => $_POST['harga_jual'][$i],
'diskon' => $_POST['diskon'][$i],
);
$this->db->where('kode_inventori',$_POST['kode_inventori']);
$this->db->where('kode_kategori_pelanggan',$_POST['kode_kategori_pelanggan'][$i]);
$this->db->update('harga_inventori',$res);
}
}
redirect("inventori");
It would help to see some of your data to know what you are trying to do. It seems a little strange that you initiate the counter $i at the same time using it as an array key in the for loop like this: for($i = 0; $i < count($_POST['harga_jual'][$i]); $i++)
It would help to know how the data in your $_POST looks like. You could try to remove the [$i] in your for loop. I would also check each POST variable it they are set before using them, something like:
for($i = 0; $i < count($_POST['harga_jual']); $i++) {
if(isset($_POST['kode_kategori_pelanggan'][$i])) {
// CHECK IF POST VARIABLES IS SET AND IF NOT SET A DEFAULT VALUE (IN THIS EXAMPLE AN EMPTY STRING):
$harga_jual = isset($_POST['harga_jual'][$i]) ? $_POST['harga_jual'][$i] : '';
$diskon = isset($_POST['diskon'][$i]) ? $_POST['diskon'][$i] : '';
$kode_inventori = isset($_POST['kode_inventori']) ? $_POST['kode_inventori'] : '';
$kode_kategori_pelanggan = $_POST['kode_kategori_pelanggan'][$i]; // ALREADY CHECKED ISSET ABOVE...
$data = array(
'harga' => $harga_jual,
'diskon' => $diskon,
);
$this->db->where('kode_inventori',$kode_inventori);
$this->db->where('kode_kategori_pelanggan', $kode_kategori_pelanggan);
$this->db->update('harga_inventori', $data);
}
}
redirect("inventori");

Deleting index of JSON Array in PHP, creating string version of index?

I'm trying to get a sampling of PHP to work but I'm having a bit of an issue.
Initially, if I just create JSON data and save it to a file the structure looks as follows
[{"id":"519d4434e39ef","title":"event 3","start":"1369108800","end":"1369195199"},
{"id":"519d4430333c1","title":"event 2","start":"1368676800","end":"1368763199"},
{"id":"519d442a2b29c","title":"event 1","start":"1368504000","end":"1368590399"}]
That is created with the following code sample
$msg = array('id' => uniqid(),
'title' => $_POST['title'],
'start' => $_POST['start'],
'end' => $_POST['end']);
$data = get_data();
array_unshift($data, $msg);
file_put_contents($data_file, json_encode($data))
But, if I try to delete an item in that set of JSON data with this
$deleteId = $_POST['id'];
$data = get_data();
$index = -1;
for($i=0; $i < count($data); $i++){
if($data[$i]['id'] == $deleteId){
$index = $i;
break;
}
}
if($index != -1){
unset($data[$index]);
}
file_put_contents($data_file, json_encode($data))
The file ends up looking like the following
{"0":{"id":"519d4434e39ef","title":"event 3","start":"1369108800","end":"1369195199"},
"2":{"id":"519d442a2b29c","title":"event 1","start":"1368504000","end":"1368590399"}}
I don't see why this is happening.
Unset preserves indexes, creating the structure you are seeing. See this answer about using splice if you want to change the array, and re-index the items.

Categories