Loop through For Loop certain number of times - php

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.

Related

php loop adds extra data to database

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(),
]);
}
}
}

How to enter multiple rows in mySQL from form data where one field changes

I've got a form which asks some basic questions about a job, and then asks to person entering to list all those colleagues that were with them at the time. What I want to do is for all colleagues present to have a row entered in to the database - so all the other details remain the same except for their work_id (which is the identifier for the person). My code below seems to submit 1 row to the db with the workID field empty
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
//Remove last part of array as extra 1 sent through by form
$workID = array_pop($varWorkID);
for ($i=0; $i < count($workID); $i++ )
{
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$workID."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";
I think I'm fairly close but I just need to get workid to be populated with each of the Work IDs for each of the employees present.
Any assistance greatly appreciated
the problem here is that you're calling $workID = array_pop($varWorkID); before you go into the loop for ($i=0; $i < count($workID); $i++ ), so the PHP interpreter thinks you just want to iterate over the length of that one element. what you actually wanted to do was pop an element off the array while inside the loop.
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
// iterate over the count of the whole array $varWorkID = $_POST['workid']
for ($i=0; $i < count($varWorkID); $i++ )
{
// now pop off the array inside the loop
//Remove last part of array as extra 1 sent through by form
$workID = array_pop($varWorkID);
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$workID."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";
now I think #Dima Fitiskin's comment proposes a better approach because you don't really need the expense of calling another function array_pop or throwing another variable on the stack $workID when you've already got an iterated reference to the index $i inside the loop.
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
// iterate over the count of the whole array $varWorkID = $_POST['workid']
for ($i=0; $i < count($varWorkID); $i++ )
{
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$varWorkID[$i]."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";

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

php array trouble

I'm a rookie with php arrays, and have a problem. I downloaded a blackjack PHP script, it stores the current players hand, deck, and dealers hand in THE $_POST, which isn't good.
So I'm trying to alter it to store them in a database instead. I'm getting errors and this is the code I'm playing with. The original code for drawing a random card from the deck is this:
shuffle($deck);
for ($i = 0; $i < 2; $i++) {
$hand[] = array_shift($deck);
$dealer[] = array_shift($deck);
}
$handstr = serialize($hand);
$deckstr= serialize($deck);
$dealerstr= serialize($dealer);
This works, but what I want to do is only draw a random card if theres no data in the database already. If the user draws, someone could just refresh the page to get a different hand. I want to do something like this:
if ($rs5[hand] == "") {
shuffle($deck);
for ($i = 0; $i < 2; $i++) {
$hand[] = array_shift($deck);
$dealer[] = array_shift($deck);
}
$handstr = serialize($hand);
$deckstr= serialize($deck);
$dealerstr= serialize($dealer);
} else {
$dealer = $rs5[dealer];
$hand = $rs5[hand];
$deck = $rs5[deck];
}
Im getting errors with this, I don't know what I'm doing with arrays really, can anyone point me in the right direction?
I'm not terribly sure what you're trying to do, but for starters:
$dealer = $rs5[dealer];
$hand = $rs5[hand];
$deck = $rs5[deck];
Should probably be:
$dealer = $rs5[$dealer];
$hand = $rs5[$hand];
$deck = $rs5[$deck];
Note the dollar signs on the index variables.
You could do:
if (empty($hand))
or:
if (count($hand) == 0)

php sql find and insert in empty slot

I have a game script thing set up, and when it creates a new character I want it to find an empty address for that players house.
The two relevant table fields it inserts are 'city' and 'number'. The 'city' is a random number out of 10, and the 'number' can be 1-250.
What it needs to do though is make sure there's not already an entry with the 2 random numbers it finds in the 'HOUSES' table, and if there is, then change the numbers. Repeat until it finds an 'address' not in use, then insert it.
I have a method set up to do this, but I know it's shoddy- there's probably some more logical and easier way. Any ideas?
UPDATE
Here's my current code:
$found = 0;
while ($found == 0) {
$num = (rand()%250)+1; $city = (rand()%10)+1;
$sql_result2 = mysql_query("SELECT * FROM houses WHERE city='$city' AND number='$num'", $db);
if (mysql_num_rows($sql_result2) == 0) { $found = 1; }
}
You can either do this in PHP as you do or by using a MySQL trigger.
If you stick to the PHP way, then instead of generating a number every time, do something like this
$found = 0;
$cityarr = array();
$numberarr = array();
//create the cityarr
for($i=1; $i<=10;$i++)
$cityarr[] = i;
//create the numberarr
for($i=1; $i<=250;$i++)
$numberarr[] = i;
//shuffle the arrays
shuffle($cityarr);
shuffle($numberarr);
//iterate until you find n unused one
foreach($cityarr as $city) {
foreach($numberarr as $num) {
$sql_result2 = mysql_query("SELECT * FROM houses
WHERE city='$city' AND number='$num'", $db);
if (mysql_num_rows($sql_result2) == 0) {
$found = 1;
break;
}
}
if($found) break;
}
this way you don't check the same value more than once, and you still check randomly.
But you should really consider fetching all your records before the loops, so you only have one query. That would also increase the performance a lot.
like
$taken = array();
for($i=1; $i<=10;$i++)
$taken[i] = array();
$records = mysql_query("SELECT * FROM houses", $db);
while($rec = mysql_fetch_assoc($records)) {
$taken[$rec['city']][] = $rec['number'];
}
for($i=1; $i<=10;$i++)
$cityarr[] = i;
for($i=1; $i<=250;$i++)
$numberarr[] = i;
foreach($cityarr as $city) {
foreach($numberarr as $num) {
if(in_array($num, $taken[]) {
$cityNotTaken = $city;
$numberNotTaken = $number;
$found = 1;
break;
}
}
if($found) break;
}
echo 'City ' . $cityNotTaken . ' number ' . $numberNotTaken . ' is not taken!';
I would go with this method :-)
Doing it the way you say can cause problems when there is only a couple (or even 1 left). It could take ages for the script to find an empty house.
What I recommend doing is insert all 2500 records in the database (combo 1-10 with 1-250) and mark with it if it's empty or not (or create a combo table with user <> house) and match it on that.
With MySQL you can select a random entry from the database witch is empty within no-time!
Because it's only 2500 records, you can do ORDER BY RAND() LIMIT 1 to get a random row. I don't recommend this when you have much more records.

Categories