I have a form repeater like this
form repeater image
which submits a code(should be same all through) a product name and a quantity in thousands. eg
code-1234 product-book Qty - 5000
code-1234 product-pen Qty -3000
code-1234 product-ruler Qty -2000
what i would like is to submit to db all the above data as a json with an incrementing id as per total number of items in this case 10,000 and the product name beside each id. The product name should end where its specific quantity end e.g when the ids reach 5000 the next id should be 5001 and the name to begin showing pen.
I have tried this `
//array submited from form
$array = $request->get('arrayName');
foreach ($array as $key => $value) {
$items[] = $value['no_of_items'];
$a_sum = array_sum($items);
$length = 15;
$string = bin2hex(openssl_random_pseudo_bytes($length));
$maxNumberOfItems = $a_sum;
for ($a = 0; $a <= $maxNumberOfItems; $a++) {
if ($a <= reset($items) && $a === $maxNumberOfItems) {
$a = reset($items);
}
echo +$a . " => " . $value['item'] . "<br> ";
$temp = bin2hex(openssl_random_pseudo_bytes($length));
$coupons[] = [
'id' => +$a,
'item' => $value['item'],
'code' => $temp,
'item_status' => 'in-store',
];
}`
It display the names correctly but does not auto increment id as explained above. The moment it reaches say 5000 the next item starts at 0 instead of 5001. Any help would be highly appreciated.
You may need to manually get the MAX(id) and do:
for ($a = $maxId; $a <= $maxNumberOfItems + $maxId; $a++)
Related
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
So I've been trying with this for a while now and can't seem to find the solution.
I have a website, selling digital good.
When the client checks out, it asks for what quantity.
I want to make it so when they type in for example, quantity 5, I want it to grab 5 stocks from the database and send all to their email.
I need to make it loop through and grab x quantity from a stock table where the assignedProduct is the product ID.
Currently, my code only getting the number of quantity and not getting different rows from my stock database. How do I make it loop the stock?
My current code is (using blockchain payment processor):
<?php
$smtp_btc = $pdo->prepare('SELECT * FROM `productitems` WHERE `avaliable` = :avaliable AND `assignedProduct` = :assignedProduct');
$smtp_btc->execute(array(':avaliable' => '0', ':assignedProduct' => $product_id));
$query = $smtp_btc->fetchAll();
// Select all from stock where avaliable = true and assignedProduct is the main productID
// Then make it
// Foreach loop here
$i = 0;
$maxiterations = $quantity - 1;
$message = '';
foreach($query as $row_product) {
while($i <= $maxiterations) {
$i++;
$product_link_stock = $row_product['code'];
$stock_id_stock = $row_product['id'];
$message = "<tr style='background: #eee;'><td><strong>Email/Username:Pass(".$i."):</strong> </td><td>$product_link_stock</td></tr>";
echo $message.'<br>';
}
}
?>
You have two loops, a foreach loop and a while loop. The data is being set once in the outer foreach loop, apparently to the first line of the query result or there may only be one result.
And then you're just printing the same data 3 times from the while loop.
Going up to the top:
$query = $smtp_btc->fetchAll();
What is the actual contents of $query here? Is it just 1 record?
So it turns out I need to do my query inside of my while loop so it can change the row it selects for each quantity.
This is my working code:
$i = 1;
$maxiterations = $quantity;
while($i <= $maxiterations) {
$smtp_btc = $pdo->prepare("SELECT * FROM `productitems` WHERE `avaliable` = :avaliable AND `assignedProduct` = :assignedProduct LIMIT $maxiterations");
$smtp_btc->execute(array(':avaliable' => '0', ':assignedProduct' => $product_id));
$query = $smtp_btc->fetchAll();
foreach($query as $row_product) {
$product_link_stock = $row_product['code'];
$stock_id_stock = $row_product['id'];
$message .= "<tr style='background: #eee;'><td><strong>Email/Username:Pass(".$i."):</strong> </td><td>$product_link_stock</td></tr>";
// Update stock foreach stock product they require (quantity depends on this)
$updateStock = $pdo->prepare('UPDATE `productitems` SET `avaliable` = :avaliable WHERE `id` = :id');
$updateStock->execute(array(':avaliable' => '1', ':id' => $stock_id_stock));
$i++;
}
$i++;
}
I was messing around with the steam API and I found out that I was not able to get the quantity of my items. Lets say I have item A 2 times, it does not show the picture just 1 time with the quantity set to "2", but instead it shows the item twice with the quantity set to 1.
This is the part I use to get the inventory.
$backpackURL = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" . $APIkey . "&SteamID=" . $profile . "&format=json";
$schemaURL = "http://api.steampowered.com/IEconItems_440/GetSchema/v0001/?key=" . $APIkey . "&language=en";
$userBackpack = json_decode(file_get_contents($backpackURL), true);
$itemSchema = json_decode(file_get_contents($schemaURL), true);
$backpack_items = $userBackpack['result'];
$schema_items = $itemSchema['result'];
And here I list all the items:
foreach($backpack_items['items'] as $ind=>$backpack_items){
$id = $backpack_items['id'];
$defindex = $backpack_items['defindex'];
$name = getItemName($schema_items, $defindex, $image_url);
$quantity = $backpack_items['quantity'];
$inventory = $backpack_items['inventory'];
echo '
$tmp[] = $backpack_items; print_r($tmp)
';
}
Since there is no ID to see if there are any duplicates, you can try to merge them by name.
By reading this code, it first creates a copy of the main array.
I loop over the main array, then again over the copy. So for each value of the main array, a complete cycle of the array is done again for values to compare against.
Since it is expected that there is atleast 1 name, I don't unset immidiatly, but only after another result is found, hence the $b.
It's quantity is increased if a dupe is found, on the key of the main loop.
$copy = $backpack_items['items'];
foreach($backpack_items['items'] as $k => $v){
$b = false;
$s = '';
$n = getItemName($schema_items, $v['defindex'], $s);
foreach($copy as $k2 => $v2){
if($n == getItemName($schema_items, $v2['defindex'], $s)){
if(!$b){
$b = $k;
} else {
unset($backpack_items['items'][$k2]);
$backpack_items['items'][$k]['quantity'] += 1;
}
}
}
}
// Now use your original loop, and the dupes should be removed.
I have a table that contains a list of all products and before each one there is a field "number" in which the user will put the quantity then click on save.
This code save all rows in data base using mutiple-insert but I want that if quantite is null or empty, so do not save this row , I want just save
$managerAchat = new AchatManager($db);
if(isset($_POST['ajouter']))
{
$size = count($_POST['quantite']);
$i = 0;
while ($i < $size)
{
if(isset($_POST['quantite'][$i]))
{
$nomProd = $_POST['nomProd'][$i] ;
$prixProd = $_POST['prixProd'][$i] ;
$quantite = $_POST['quantite'][$i] ;
$date = date('d/m/Y');
$AchatObject = new Achat(array(
'nomProd' => $nomProd ,
'prixProd' => $prixProd ,
'quantite' => $quantite ,
'date' => $date ,
)) ;
$managerAchat->insert($AchatObject);
++$i;
}
}
}
It seems you just need to change:
if(isset($_POST['quantite'][$i]))
to:
if(isset($_POST['quantite'][$i]) && $_POST['quantite'][$i] > 0)
You can also use for example array_filter() to loop only over the keys that have an amount set:
if(isset($_POST['ajouter']))
{
$has_amounts = array_filter($_POST['quantite']);
foreach (array_keys($has_amounts) as $key)
{
$nomProd = $_POST['nomProd'][$key];
// etc.
I'm not 100% sure this is correct as your question and code are not clear. But, you can check to see if $_POST['quantite'][$i] is empty (zero and null will both be considered empty) and skip them if they are:
if(isset($_POST['quantite'][$i]) && !empty($_POST['quantite'][$i]))
I have database that contains scores which are stored daily. I want to average each months scores for each user. So far I have this:
DB structure:
id | name | tscore | added
int| string | float(100 or less)| date(2014-01-01 16:34:22)
Code:
while($row = mysql_fetch_assoc($getChartData)){ // Data from MySQL
$added_date = explode(' ',$row['added']); // Date formate 2014-01-01 16:34:22
$chartData[] = array(
'id' => $row['name'],
'tscore' => $row['tscore'],
'added' => $added_date[0] // Here I take the month only
);
}
if($_POST['range'] == 'month'){
foreach($chartData as $key => $value){
$added = explode('-',$chartData[$key]['added']);
$count = 1;
foreach($chartData as $key2 => $value2){
$added2 = explode('-',$chartData[$key2]['added']);
if($chartData[$key]['id'] === $chartData[$key2]['id'] && $added[1] === $added2[1]){ // if user is the same and the month is the same, add the scores together, increment counter, and unset 2nd instance
$chartData[$key]['tscore'] = ((float)$chartData[$key]['tscore'] + (float)$chartData[$key2]['tscore']);
$count++;
unset($chartData[$key2]);
}
}
$chartData[$key]['tscore'] = ($chartData[$key]['tscore']/$count); // Average all the scores for the month.
}
}
The problem is this method is deleting all the elements of the $chartData array. What can I try to resolve this?
You should try to solve it with MySQL. Try something like this (replace 'your_scores_table' with your table name):
SELECT
Score.name,
AVG(Score.tscore) AS `avg`,
CONCAT(YEAR(Score.added), '-', MONTH(Score.added)) AS `year_month`
FROM
your_scores_table AS Score
GROUP BY
Score.name ASC,
YEAR(Score.added) DESC,
MONTH(Score.added) DESC
;
Your logic is wrong. You are looping through the same array twice. Which means that the following if will always evaluate to true which means that array item will always get unset
//This will always be true
if($chartData[$key]['id'] === $chartData[$key2]['id'] && $added[1] === $added2[1]){
It may be simpler for you to create another array where you keep your scores. Something like
$aScores = array();
$count = 1;
foreach($chartData as $key => $value){
//Add score to a different array
$aScores[$value['name']]['tscore'] = (($aScores[$value['name']]['tscore'] + $value['tscore']) / $count);
$count++;
}
Also I would look into the MySQL AVG function. You could use that to save you having to do it in PHP