Each input->post is a key/value array. Each value inside of each array matches up to the rest of the array values. So the first row in the database insertion will be all of the data from all of the array's key 0. The second will be 1 and so on and so on. How would I take all of the data from the post arrays and insert them into the database using this method?
$selected_size = $this->input->post('selected_size');
$product_id = $this->input->post('product_id');
$product_name = $this->input->post('product_name');
$product_color = $this->input->post('product_color');
$cookie_id = $this->input->cookie("cookie_id");
$q1 = $this->db->query("SELECT * FROM default_cart_temp
WHERE cookie_id = '$cookie_id'
AND is_paid = 'No'");
if ($q1->num_rows() > 0) {
} else {
print_r($selected_size);
/*$data = array('selected_size' => $selected_size,
'product_id' => $product_id,
'product_name' => $product_name,
'product_color' => $product_color);
$this->db->insert('mytable', $data);*/
}
Assuming your insert() method takes an associative array and then builds and executes the insert statement:
foreach($product_id as $key => $value)
{
$data = array(
'selected_size' => $selected_size[$key],
'product_id' => $value,
'product_name' => $product_name[$key],
'product_color' => $product_color[$key]
);
$this->db->insert('mytable', $data);
}
By using a foreach on one of the arrays and obtaining the key on each iteration, you can use the same key variable to access the corresponding element in each other array.
Related
What I'm trying to do is preserve the order of an array, while determining if each of the numbers match numbers that were pulled from the database. What I have is an array of numbers ($ids), and a non empty array of rows ($rows)
$images = array();
$ids = array(
0 => '41',
1 => '42',
2 => '43',
3 => '44'
);
// database example
$rows = array(
0 => array(
'name' => 'John Doe',
'id' => '42'
),
1 => array(
'name' => 'Jane Doe',
'id' => '43'
),
);
$i = 0;
foreach ($rows as $row) {
// This works, but it doesn't preserve the order of the $ids array
if (in_array($row['id'], $ids[$i])) {
// add $id to a new array
// or use the same $id array
$images[$i]['name'] = $row['name'];
$images[$i]['id'] = $row['id'];
$i++;
}
}
Any help would be appreciated.
Since id is unique in the rows from your database, you can index the $rows array by id to make it easier to look up values there. You can do this with array_column like this:
$rows = array_column($rows, null, 'id');
Or add them to $rows using id as index as you fetch them from the db like this:
while ($row = //whatever query result/prepared statement fetch you're using) {
$rows[$row['id']] = $row;
}
Then, instead of iterating $rows, you can iterate $ids. This will ensure that the resulting $images array will be in the same order as $ids.
foreach ($ids as $id) {
if (isset($rows[$id])) {
$images[] = [
'name' => $rows[$id]['name'],
'id' => $rows[$id]['id']
];
}
}
Another thing that might make this easier (unless you're using the non-matching rows for something else), would be to use the $ids array as a parameter to a WHERE id IN clause in the query that's selecting $rows, so you won't have to do that filtering in PHP. Here's a Q&A that shows how to do that with PDO, for example: PHP - Using PDO with IN clause array.
You could iterate over ids array instead. It will be something like this:
foreach($ids as $id) {
$data = find($id, $rows);
if ($data === null) {
continue;
}
$images[] = [
'name' => $data['name'],
'id' => $data['id']
];
}
function find($id, $rows) {
foreach($rows as $row) {
if($row['id'] == $id) {
return $row;
}
}
return null;
}
Totally agree with #Don't Panic, you should fetch only the data you'll use if possible.
I know this is a basic question and I'm sorry I can't answer, but how can I create 2 collections based from an array with 2 values in Laravel/PHP? Here's my code:
$received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
foreach($received_items as $received_item) {
$product_ids = $received_item->product_id;
foreach($product_ids as $product_item_no => $product_id) {
$products = Product::where('id', '=', $product_id);
$voucher_cost = $products->value('cost');
$qty_addend = $received_item->qty_per_item;
$list = array(
'product_item_no' => $product_item_no + 1,
'product_name' => $products->value('name'),
'size' => $products->value('size'),
'qty_addend' => $qty_addend[$product_item_no],
'voucher_cost' => $voucher_cost,
'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
);
$list = (object)$list;
$received_item->list = $list;
$data = collect([$list]);
}
}
return $data;
Basically, the $product_ids is the array I want to get and count($product_ids) is returning 2, but it's just creating the collection from the 2nd array value. See screenshot below:
screenshot.png
Any help is much appreciated.
In your $list variable it will only store last product_id data, because you have to take $list as multi-dimensional array.
You have to take $list variable out of the second loop, so it not overwrite data.
Try below code:
$received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
foreach($received_items as $received_item) {
$product_ids = $received_item->product_id;
$list = []; // declare list variable here
foreach($product_ids as $product_item_no => $product_id) {
$products = Product::where('id', '=', $product_id);
$voucher_cost = $products->value('cost');
$qty_addend = $received_item->qty_per_item;
$list[] = array( // make it multi-dimentional array
'product_item_no' => $product_item_no + 1,
'product_name' => $products->value('name'),
'size' => $products->value('size'),
'qty_addend' => $qty_addend[$product_item_no],
'voucher_cost' => $voucher_cost,
'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
);
}
// take this code out of loop
$list = (object)$list;
$received_item->list = $list;
$data = collect([$list]);
}
return $data;
I've been trying to insert multiply items using foreach loop in php and mysql. When i insert its insert null values. any ideas as to what i should fix?
$itemNo = $statement->fetchColumn();
$item_name = ($_POST["item_name"]);
$item_price = ($_POST["item_price"]);
$item_quantity = ($_POST["item_quantity"]);
$item_total = ($_POST["item_total"]);
$statement = $connect->prepare("
INSERT INTO product
( `item_no`,`item_name`, `item_price`, `item_quantity`, `item_total`)
VALUES ('$itemNo','$item_name','$item_price','$item_quantity','$item_total')
");
foreach($_POST["item_name"] as $subscription){
$statement->execute(
array(
':itemNo' => $itemNo,
':item_name ' => trim($_POST["item_name"]),
':item_price' => trim($_POST["item_price"]),
':item_quantity' => trim($_POST["item_quantity"]),
':item_total' => trim($_POST["item_total"])
)
);
}
You need to put placeholders in the query, not variables, to match the parameters in the call to execute().
$statement = $connect->prepare("
INSERT INTO product
( `item_no`,`item_name`, `item_price`, `item_quantity`, `item_total`)
VALUES (:itemNo,:item_name,:item_price,:item_quantity,:item_total)
");
And if $_POST['item_name'] is an array, you can't use trim($_POST['item_name']) as a value. The argument to trim() has to be a string, not an array. If these post variables are all arrays, you need to index them.
foreach ($item_name as $index => $subscription) {
$statement->execute(
array(
':itemNo' => $itemNo,
':item_name ' => trim($subscription),
':item_price' => trim($item_price[$index]),
':item_quantity' => trim($item_quantity[$index]),
':item_total' => trim($item_total[$index])
)
);
}
how to update plan with vendor_plan_task_status_mapp table.
the model for plan update is
public function updatePlanData(){
$planId = $this->input->post('plan_id');
$data = array(
'plan_title' => $this->input->post('plan_title'),
'plan_price' => $this->input->post('plan_price'),
'plan_desc' => $this->input->post('plan_desc')
);
$this->db->where('plan_id', $planId);
$this->db->update('tbl_plan', $data);
$this->db->where('plan_id',$planId);
$this->db->delete('plan_task_mapping');
foreach ($this->input->post('task_id') as $key => $value)
{
$data2 = array(
'plan_id' => $planId,
'task_id' => $value
);
// echo "Index {$key}'s value is {$value}.";
$this->db->insert('plan_task_mapping', $data2);
}
//-------- HEAR I NEED A CODE TO UPDATE The V_T_S_M table-----------
}
after 1st table update i want to update the data in vendr_task_status_mapping table?????
IN THIS ANSWER YOU GET AN ERROR IF YOU CHANGE THE PLAN BUT USING THIS CODE YOU HAVE TO SIMPLY EDIT AND UPDATE IT ANGIN AND THIS MODEL IS CREATE A NEW ID FOR YOUR TASK AND INSERT IT AGAIN.
public function vendorUpdateModel($data)
{
$vendor_id = $this->input->post('vendor_id');
$data = array(
'category_id' => $this->input->post('category_id'),
'plan_id' => $this->input->post('plan_id'),
'city_id' => $this->input->post('city_id'),
'business_name' => $this->input->post('business_name'),
'owner_name' => $this->input->post('owner_name'),
'contact_no1' => $this->input->post('contact_no1'),
'contact_no2' => $this->input->post('contact_no2'),
'vendor_email' => $this->input->post('vendor_email'),
'subscription_date' => $this->input->post('subscription_date'),
'vendor_description' => $this->input->post('vendor_description'),
'vendor_address' => $this->input->post('vendor_address')
);
$this->db->where('vendor_id', $vendor_id);
$this->db->update('vendor',$data);
$this->db->where('vendor_id',$vendor_id);
$this->db->delete('vendor_task_status_mapping');
$this->db->select('task_mapp_id');
$this->db->where('plan_id',$this->input->post('plan_id'));
$query = $this->db->get('plan_task_mapping');
foreach($query->result() as $row)
{
$data2 = array(
'task_mapp_id' => $row->task_mapp_id,
'vendor_id' => $vendor_id,
'task_status' => '0'
);
$this->db->insert('vendor_task_status_mapping', $data2);
}
return;
}
If you added one field in plan_task_mapping table for add unique number then... As you mention your code:
$unique=array();
foreach ($this->input->post('task_id') as $key => $value)
{
$no=rand(0, 15);
$data2 = array(
'unique_no'=>$no,
'plan_id' => $planId,
'task_id' => $value
);
$unique[] = $no; //store no in array to use it.
// echo "Index {$key}'s value is {$value}.";
$this->db->insert('plan_task_mapping', $data2);
}
Before deleting plan_task_mapping table data. fetch that data.
function select()
{
$this->db->where('plan_id',$planId);
$Q = $this->db->get('plan_task_mapping');
if($Q->num_rows() > 0)
{
foreach ($Q->result_array() as $row)
{
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
Then delete the data as you mention in you code:
$this->db->where('plan_id',$planId);
$this->db->delete('plan_task_mapping');
Then delete that old data from VTSM table:
$this->db->where('vendor_plan_task_mapping_id',$data[0]['id']); //this data[0]['id'] come form select(). change field name if required.
$this->db->delete('VTSM');
Here fetch that new inserted data by that unique no: //which we stored it in array.
foreach($unique as $u_no)
{
$this->db->where('unique_no',$u_no);
$Q = $this->db->get('plan_task_mapping');
if($Q->num_rows() > 0)
{
foreach ($Q->result_array() as $row1)
{
$plan[] = $row1;
}
}
$Q->free_result();
return $plan;
}
In above code we have fetched that new inserted data to get their id to insert status.
Now inserting status:
foreach($plan as $a)
{
$Sdata=array(
"plan_task_mapping_id"=>$a['id'], //this is new id change name if required
"status"="your new status");
$this->db->insert('VTSM',$Sdata);
}
Use $this->db->insert_batch(); instead of inserting in foreach loop.
Check at this link how to use it.
This seems like a simple challenge, but I'm struggling.
I want to retrieve records using a join query on two database tables and represent them as an array of arrays, whereby each of the elements in the root array is a parent record and each nested element represents a child record.
The SQL query is working fine, and it returns a set of rows in which the channel_key column is a grouping column.
Here's my attempt at populating the array structure from the rows:
$rows = $db->get_results($query);
$key = '';
$programmes = array();
foreach ($rows as $row) {
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
$programmes[] = $programme;
if ($key != $row->channel_key) {
$channels[] = array(
'key' => $row->channel_key,
'programme' => $programmes
);
$key = $row->channel_key;
$programmes = array();
}
}
Unfortunately this only populates the root level arrays (the ones that correspond to the parent records).
Any suggestions please?
Thanks,
Tim
You only have one programme in the $programmes array when you assign it to the channel.
An alternative would be to build the channel array with the channel_key.
e.g.
<?php
$channels = array();
foreach($rows as $row) {
// Create the channel node if it doesn't exist
if (!isset($channels[$row->channel_key])) {
$channels[$row->channel_key] = array(
'key' => $row->channel_key,
'programme' => array()
);
}
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
// Add to the existing channel node.
$channels[$row->channel_key]['programme'][] = $programme;
}
Simple solution can be.
$rows = $db->get_results($query);
$key = '';
$programmes = array();
foreach ($rows as $row) {
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
$programmes[$row->channel_key][] = $programme;
}