php loop adds extra data to database - php

I have loop to store my data and it multiple the rows.
example
I have 3 rows with value of test1 and I need to add this rows to become 5
so I have 3 rows already
I add number in input field 2
I loop this 2 number and create new rows
previously 3 rows + 2 new rows = 5 rows in total
but currently I am getting 9 rows.
Code
foreach($request->input('barcodes') as $bb)
{
for ($i = 0; $i < $request->input('nonuiqueAmount'); ++$i) {
$barcode = new Barcode;
$barcode->product_id = $product->id;
$barcode->returned = false;
$barcode->serial_number = $bb['serial_number'];
$barcode->save();
}
}
In case you need a full code with logic here I shared it for you.
Any idea why I get more than my desire rows?

Solved
Thanks to u_mulder suggestion here is how I solved my issue
foreach($request->input('barcodes') as $bb)
{
$bbb = $bb['serial_number']; // added to get single serial number
}
for ($i = 0; $i < $request->input('nonuiqueAmount'); ++$i) {
$barcode = new Barcode;
$barcode->product_id = $product->id;
$barcode->returned = false;
$barcode->serial_number = $bbb; // changed
if($barcode->save()) {
$user = Auth::user();
$outlets = $user->outlets;
foreach($outlets as $outlet) {
DB::table('outlet_products')->insert([
'outlet_id' => $outlet->id,
'barcode_id' => $barcode->id,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
}

Related

laravel multiple tables exploded data

I have this tables where I have inserted multiple imploded data which I can immediately pull from the database as it is just the ID of another table however I cannot show their names on the table
I have an Incident_Table and IncidentType_table I can already show the data but I'm still missing a few things to show the data on my tables instead of just showing 1,3 in my views it should be
1-Police
2-Fire Fighters
3-Ambulance
4-Others
regarding on my code this is what I have so far
public function index()
{
$Incidents = Incident::all(); // I get 1,3 as a collection
// 1 - Police and 3 - Ambulance
foreach ($Incidents as $incident) {
$request_responder = explode(",", $incident->response_needed_id);
for ($i = 0; $i < count($request_responder); $i++) {
$requested_responder[] = ResponderType::with('incident')->get()->where('id', '=', $request_responder[$i]);
}
$requested_responder = implode(',', $request_responder);
}
dd($requested_responder); //show only 1,3 should be Police, Ambulance
return view('dispatch.index', compact('Incidents'));
}
Without seeing your blade template or model, it is difficult to see where the values "1-Police 2-Fire Fighters 3-Ambulance 4-Others" would come from. However, you can solve your current problem from within this current scope by using this.
public function index()
{
$Incidents = Incident::all(); // I get 1,3 as a collection
$incident_type = ['Police', 'Fire Fighters', 'Ambulance', 'Others']; // 1 - Police and 3 - Ambulance
foreach ($Incidents as $incident) {
$request_responder = explode(",", $incident->response_needed_id);
for ($i = 0; $i < count($request_responder); $i++) {
$requested_responder[] = ResponderType::with('incident')->get()->where('id', '=', $request_responder[$i]);
}
$requested_responder = implode(', ', $incident_type[$request_responder-1]); // We minus 1 because the array starts from 0
}
return view('dispatch.index', compact('Incidents', 'requested_responder'));
}

Loop through For Loop certain number of times

Okay, I know the question is a bit ambiguous but here I go. I have a dynamic form with 4 inputs. These dynamic fields on the form can generate multiple times.
What I intend to achieve is this the input field repeat with amount 100 is supposed to be inserted 4 times same as amount 200 and same as amount 300 so in total, I should have a total of 12transactions with the different amounts there. I already have the code set up for inserting the dynamic field into the database excluding the repeat input field. I cannot seem to wrap my mind as to how I can do the above explanation. Please Help
$bulkRecipientTransfer = $Request->bulkRecipientTransfer; //array
$bulkTransferType = $Request->bulkTransferType; //array
$bulkAmountTransfer = $Request->bulkAmountTransfer;//array
$bulkCountTransfer = $Request->transferCount; //array
for( $i =0; $i < count($bulkRecipientTransfer);) {
$commandId = MpesaB2B::query()->where('id',$bulkTransferType[$i])->pluck('commandID')->first();
$this_contact = array(
$bulkRecipientTransfer[$i],
$bulkTransferType[$i],
$bulkAmountTransfer[$i],
$bulkCountTransfer[$i]
);
$_amount = $bulkAmountTransfer[$i];
$_bulkRecipientTransfer = $bulkRecipientTransfer[$i];
$CountTransfer = $bulkCountTransfer;
$insertData = [
'AccountReference' =>$narration,
'TransactionAmount' =>(int)str_replace(',', '', $_amount),
'Status' =>0,
'credit_party' =>$_bulkRecipientTransfer,
'debit_party' =>$sender,
'CommandID' =>$commandId,
'SystemType' =>'externalbulk'
];
B2BTransfer::insert($insertData);
}
For the second loop, this may work. I am not sure if I got your question correctly though. This would allow you to add each of those entries four times into the database.
for( $i =0; $i < count($bulkRecipientTransfer);) {
$commandId = MpesaB2B::query()->where('id',$bulkTransferType[$i])->pluck('commandID')->first();
$this_contact = array(
$bulkRecipientTransfer[$i],
$bulkTransferType[$i],
$bulkAmountTransfer[$i],
$bulkCountTransfer[$i]
);
$_amount = $bulkAmountTransfer[$i];
$_bulkRecipientTransfer = $bulkRecipientTransfer[$i];
$CountTransfer = $bulkCountTransfer;
$insertData = [
'AccountReference' =>$narration,
'TransactionAmount' =>(int)str_replace(',', '', $_amount),
'Status' =>0,
'credit_party' =>$_bulkRecipientTransfer,
'debit_party' =>$sender,
'CommandID' =>$commandId,
'SystemType' =>'externalbulk'
];
for($j = 0; $j < $CountTransfer; $j++) {
B2BTransfer::insert($insertData);
}
}
```
Okey, thank you all for your assistance on this. Well due to client pressures and issues with timelines i had to find a way out of this by doing the following;
for($i=0; $i< count($bulkRecipientTransfer); $i++){
$stagingTransfer = new MpesaStaging;
$stagingTransfer->credit_party = $Request->bulkRecipientTransfer[$i];
$stagingTransfer->debit_party = $Request->sender;
$stagingTransfer->AccountReference = $Request->bulkNarration[$i];
$stagingTransfer->TransactionAmount = (int)str_replace(',', '', $Request->bulkAmountTransfer[$i]);
$stagingTransfer->Status = 1;
$stagingTransfer->SystemType = 'externalbulk';
$stagingTransfer->CommandID = $Request->bulkTransferType[$i];
$stagingTransfer->repeatCount = $Request->transferCount[$i];
$stagingTransfer->save();
}
//Fetch the stored transactions here
$fetchStaging = MpesaStaging::query()->where('Status',1)->get();
foreach($fetchStaging as $key=>$queue){
$transactionCountStart = 1;
$TransactionAccountRefDate = date('dmy');
for($i=0; $i < $queue->repeatCount; $i++){
$commandId = MpesaB2B::query()->where('id',$queue->CommandID)->pluck('commandID')->first();
$transferSchedule = new B2BTransfer;
$transferSchedule->AccountReference = $queue->AccountReference.$transactionCountStart++.$TransactionAccountRefDate;
$transferSchedule->TransactionAmount = $queue->TransactionAmount;
$transferSchedule->Status = 0;
$transferSchedule->credit_party = $queue->credit_party;
$transferSchedule->debit_party = $queue->debit_party;
$transferSchedule->CommandID = $commandId;
$transferSchedule->SystemType = $queue->SystemType;
$transferSchedule->save();
}
$updateScheduledPayments = MpesaStaging::query()->where('id',$queue->id)->delete();
}
Capture the Number of dynamic rows generated. Then Store them on a staging table.
Extract the RepeatCount captured for each transaction Amount and use a for loop to process the RepeatCount number of transactions to be queued.Then delete the already processed staged transaction based on the queue id.

Codeigniter generate increment ID for looping

i want to import excel as json data in Codeigniter with generate id.
my model
public function generateImpId() {
$now = date('ymd');
$check = "SELECT COUNT(*) as count FROM OP_IMP_15 WHERE DATE(OP_IMP_15.created_at) = DATE(NOW())";
$querycheck = $this->db->query($check);
$id = $querycheck->row()->count;
return 'IMPDEMO'.$now.str_pad($id, 4, '0', STR_PAD_LEFT);
}
my controller
//count row
$lastRow = $objPHPExcel->setActiveSheetIndex($sheetnumber)->getHighestRow();
$countrow = $lastRow - 1;
//start loop excel from 2nd row. Row 1 is title row
for ($j=2; $j < $lastRow; $j++ ){
$myArray[] = array(
'site_id' => $objWorksheet->getCell('C'.$j)->getValue(),
'site_name' => $objWorksheet->getCell('D'.$j)->getValue(),
'id_site_doc'=> $objWorksheet->getCell('J'.$j)->getValue(),
'id_project_doc' => $objWorksheet->getCell('K'.$j)->getValue(),
//generate ID from model
'implementation_id' => $this->M_MRCR_A->generateImpId(),
...
the result
{ "site_id":"AR001",
"site_name":"Site AR 001",
"id_site_doc":"5df1b4223269f818adab55af",
"id_project_doc":"5da43895e619143bcff53ab1",
"implementation_id":"IMPDEMO2003310001",
"status":"implementation_created",
"endstate":false,
"created_by":"sgph_pm#mittapp.com",
"counter_mr":"0",
"tech_boq_ids":[
],
...
{ "site_id":"AR002",
"site_name":"Site AR 002",
"id_site_doc":"5df1b4223269f818adab55af",
"id_project_doc":"5da43895e619143bcff53ab2",
"implementation_id":"IMPDEMO2003310001",
"status":"implementation_created",
"endstate":false,
"created_by":"sgph_pm#mittapp.com",
"counter_mr":"0",
"tech_boq_ids":[
],
my expectation
to make "implementation_id" increment based on how many rows the data will be imported and format based on custom ID i'd made (i can't use uuid). ex:
i have 3 row to be imported, so the value of $implementation_id will be : IMPDEMO2003310001, IMPDEMO2003310002, IMPDEMO2003310003
Well since you already have the generated implementation_id value, and I have no idea what the generateImpId() function do, you could manually replace each generated implementation_id with the $j you have :
//count row
$lastRow = $objPHPExcel->setActiveSheetIndex($sheetnumber)->getHighestRow();
$countrow = $lastRow - 1;
//start loop excel from 2nd row. Row 1 is title row
for ($j=2; $j < $lastRow; $j++ ){
$implementation_id = $this->M_MRCR_A->generateImpId();
$implementation_id = substr($implementation_id, 0, -4) . str_pad($j-1, 4, '0', STR_PAD_LEFT); // since $j starts with 2
$myArray[] = array(
'site_id' => $objWorksheet->getCell('C'.$j)->getValue(),
'site_name' => $objWorksheet->getCell('D'.$j)->getValue(),
'id_site_doc'=> $objWorksheet->getCell('J'.$j)->getValue(),
'id_project_doc' => $objWorksheet->getCell('K'.$j)->getValue(),
//generate ID from model
'implementation_id' => $implementation_id,
...
You shoulnd't try to do everything in one single loop.
Maybe you should use a first iteration (for loop) to create the array, and then, a second iteration to fill this implementation_id field.
You can do this by getting the start implementation ID at the start of the loop and just increment it each time (PHP can cope with incrementing a string like this)...
$implementationID = $this->M_MRCR_A->generateImpId();
//start loop excel from 2nd row. Row 1 is title row
for ($j=2; $j < $lastRow; $j++ ){
$myArray[] = array(
// ...
//generate ID from model
'implementation_id' => $implementationID++,
that should give you values like...
IMPDEMO2003310001
IMPDEMO2003310002
IMPDEMO2003310003

Row Iteration not working

My goal is to iterate over all rows in a specific ColumnFamily in a node.
Here is the php code (using my wrapper over phpcassa):
$ring = $cass_db->describe_ring();
foreach ($ring as $ring_details)
{
$start_token = $ring_details->start_token;
$end_token = $ring_details->end_token;
if ($start_token != null && $end_token != null)
{
$i = 0;
$batch_size = 10;
$params = array(
'token_start' => $start_token,
'token_finish' => $end_token,
'row_count' => $batch_size,
'buffer_size' => 1000
);
while ($batch = $cass_db->get_range_by_token('myColumnFamily', $params))
{
var_dump('Batch# '.$i);
foreach ($batch as $row)
{
$row_key = $row[0];
$row_values = $row[1];
var_dump($row_key);
}
$i++;
//Just to stop infinite loop
if ($i > 14)
{
die();
}
}
}
}
get_range_by_token() uses default parameters overwritten by $params.
In each batch I get the same 10 row keys.
How to iterate over all existing rows in a large Cassandra DB?
I am not a PHP developer so I may misunderstand something in your code. More, you did not specify which cassandra version you are using.
Iteration on all rows is generally done starting and ending with an empty token, and redefining the start token in each iteration. In your code I can't see where you redefine token_start in each iteration. If you don't redefine it you're querying cassandra everytime for the same range of tokens and you will get always the same resultset.
Your code should do something like this ...
start_token = '';
end_token = '';
page_size = 100;
while ( get_range_by_token('cf', start_token, end_token, page_size) {
// here I should get page_size rows (unless I'm in last iteration or table rows is smaller than page_size elements)
start_token = rows[rows.size()].getKey();
}
HTH,
Carlo

DynamoDb retrieve data Order by descending order and then use pagination like sql syntax

I am facing problem to retrieve records in descending order with pagination limit from amazon dynamodb as in mysql.
Now I am using the following script, but it gives unordered list of records. I need the last inserted id is on top.
$limit = 10;
$total = 0;
$start_key = null;
$params = array('TableName' => 'event','AttributesToGet' =>array('id','interactiondate','repname','totalamount','fooding','nonfooding','pdfdocument','isMultiple','payment_mode','interaction_type','products','programTitle','venue','workstepId','foodingOther','interaction_type_other'), 'ScanFilter'=> array('manufacturername' => array("ComparisonOperator" => "EQ", "AttributeValueList" => array(array("S" => "$manufacturername")))),'Limit'=>$limit );
$itemsArray = array();
$itemsArray = array();
$finalItemsArray = array();
$finalCRMRecords = array();
do{
if(!empty($start_key)){
$params['ExclusiveStartKey'] = $start_key->getArrayCopy();
}
$response = $this->Amazon->Dynamodb->scan($params);
if ($response->status == 200) {
$counter = (string) $response->body->Count;
$total += $counter;
foreach($response->body->Items as $itemsArray){
$finalItemsArray[] = $itemsArray;
}
if($total>$limit){
$i =1;
foreach($response->body->Items as $items){
$finalItemsArray[] = $items;
if($i == $limit){
$start_key = $items->id->{AmazonDynamoDB::TYPE_NUMBER}->to_array();
$finalCRMRecords['data'] = $finalItemsArray;
$finalCRMRecords['start_key'] = $start_key;
break;
}
$i++;
}
}elseif($total<$limit){
$start_key = $response->body->LastEvaluatedKey->to_array();
}else{
$finalCRMRecords['data'] = $finalItemsArray;
if ($response->body->LastEvaluatedKey) {
$start_key =$response->body->LastEvaluatedKey->to_array();
break;
} else {
$start_key = null;
}
$finalCRMRecords['start_key'] = $start_key;
}
}
}while($start_key);
Regards
Sandeep Kumar Sinha
A Scan operation in DynamoDB can not change the sorting of the returned items. Also is Scan a pretty expensive operation as it always requires to read the whole table.
If you want to take advantage of DynamoDB, here's one advice:
Instead of looking for information, try to just find it.
In the sense of, use lookups instead of scan/query to get the information you need.
As an example, if you have a table that stores Events. Just store all events in that table, with their EventId as HashKey. Then you can have a second table EventLookups to store lookups to EventIds. In the EventLookups table you could put an Item like LookupId: LATEST-EVENT referencing some EventId: .... Every time you insert new events you can update the LATEST-EVENT entry to point to a newer Event. Or use a SET to store the latest 50 EventIds events in one Item.
-mathias

Categories