php remove duplicate values and show one - php

<?php
include ("../pos/db_config/db_config.php");
include ("../pos/functions/select.php");
$i = 0;
$sql = topsalep($idCompany);
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$end_sale_date = $row["end_sale_date"];
$name = $row["name"];
$tot_s = $row["tot_price"];
$qc = $row["sales_item_qty"];
$proResult[$i][0] = $name;
$proResult[$i][1] = $end_sale_date;
$proResult[$i][2] = $tot_s;
$proResult[$i][3] = $qc;
$i++;
}
//$name = $proResult[0][0];
//echo "$name";
for ($i = 0; $i < $result->num_rows; $i++) {
$count = 0;
$name = $proResult[$i][0];
$date = $proResult[$i][1];
$price = $proResult[$i][2];
$qct = $proResult[$i][3];
$totalPrice = 0;
for ($j = 0; $j < $result->num_rows; $j++) {
if ($proResult[$j][1] == $date && $proResult[$j][0] == $name) {
$x = $proResult[$j][2];
$count++;
$totalPrice+=$x;
}
}
$name = $proResult[$i][0];
$date = $proResult[$i][1];
$price = $proResult[$i][2];
for ($k = 0; $k < $count; $k++){
if($proResult[$k][1] == $date && $proResult[$k][0] == $name)
{
}
}
echo "Name : $name <br>";
echo "End Date : $date : Count $count : total = $totalPrice <br><br>";
?>
In this code I showed Last 5 days product vise total value. A one day can happen same sale id there different quantity of products. Then finally I calculated the one product wise total sale value. But problem is duplicate it.
In my join query I used distinct But I want show my PHP code when duplicated values only show one value.
enter image description here
enter image description here

Related

How to access and return specific value of a foreach in PHP

So I have a request-response that looks like this
$json='[ {"item_cat":"Stationary","items":[{"item_name":"A4 Paper","qty":"2"},{"item_name":"Test Paper","qty":"6"}],"total":"2"},
{"item_cat":"Computer Accessory ","items":[{"item_name":"Power pack","qty":"2"}],"total":"1"},
{"item_cat":"Material","items":[{"item_name":"T-Shirt","qty":"3"},
{"item_name":"Cap","qty":"5"}],"total":"2"}]';
I'm trying to get each item_name and qty so I can use them to manipulate my db. Here is what I've done
$data = json_decode($json, true);
$len = count($data);
for($i =0; $i< $len; $i++){
$item_length = count($data[$i]['items']);
for($c=0; $c < $item_length; $c++){
foreach ($data[$i]['items'][$c] as $key => $value ) {
$qty = '';
if($key == "qty"){
$qty = $data[$i]['items'][$c];
}
if($key == 'item_name'){
$item_name = "$value";
}
$sql= $db->query("SELECT `stock` from `inventory` WHERE `item_name` = '$item_name'");
while ($sql1 = $sql->fetch_assoc()) {
$stock = $sql1['stock'];
}
if($stock > $qty ){
$stock_balance = $stock - $qty;
$quantity = (int)$qty;
$db->query("UPDATE `inventory` SET `stock` = (`stock` - '$quantity') WHERE `item_name` = '$item_name'");
}else{
echo "<h3> This Operation Not Allowed: Stock Balance Is Less Than The Request <h3>";
}
}
}
}
A non-numeric value encountered, which is as a result of $qty because I'm not able to return just qty value. I've tried several other means. I'm really exhausted. Would appreciate any help please. Cheers!
Let's decompose your code.
This is json:
[
{
"item_cat":"Stationary",
"items":[
{
"item_name":"A4 Paper",
"qty":"2"
},
{
"item_name":"Test Paper",
"qty":"6"
}
],
"total":"2"
},
{
"item_cat":"Computer Accessory ",
"items":[
{
"item_name":"Power pack",
"qty":"2"
}
],
"total":"1"
},
{
"item_cat":"Material",
"items":[
{
"item_name":"T-Shirt",
"qty":"3"
},
{
"item_name":"Cap",
"qty":"5"
}
],
"total":"2"
}
]
Now the array loop without the SQL (to ensure that it works as expected):
$data = json_decode($json, true);
$len = count($data);
for($i =0; $i< $len; $i++){
$item_length = count($data[$i]['items']);
for($c=0; $c < $item_length; $c++){
foreach ($data[$i]['items'][$c] as $key => $value ) {
$qty = '';
if($key == "qty"){
$qty = $data[$i]['items'][$c];
}
if($key == 'item_name'){
$item_name = "$value";
}
The problems here are: un-human variable names and not correct working with JSON object.
First of all, let us rename variables to something readable.
Example:
$data[$i] will be $catalog_entry (object)
$data[$i]['items'] will be $catalog_entry_items (array)
$data[$i]['items'][$c] will be $catalog_entry_item (one item, object)
Let's change the code with new variables:
$data = json_decode($json, true);
$len = count($data);
for($i =0; $i< $len; $i++) {
$catalog_entry = $data[$i];
$catalog_entry_items = $data[$i]['items'];
for($c=0; $c < sizeof($catalog_entry_items); $c++) {
$catalog_entry_item = $data[$i]['items'][$c];
$qty = $catalog_entry_item['qty'];
$item_name = $catalog_entry_item['item_name'];
echo $item_name . ' : ' . $qty . "\n"; // <-- this is for testing
}
}
Run this code and see the expected result:
A4 Paper : 2
Test Paper : 6
Power pack : 2
T-Shirt : 3
Cap : 5
Good, now we have qty and item_name.
Let's make queries. First look at your code:
$sql= $db->query("SELECT `stock` from `inventory` WHERE `item_name` = '$item_name'");
while ($sql1 = $sql->fetch_assoc()) {
$stock = $sql1['stock'];
}
Two strange things: 1) possible SQL injection, 2) replace $stock variable many times with new value (if we have more than 1 row for item in inventory).
Anyway, if this code is working (I can't check), then we come to next part:
if ($stock > $qty ) {
$stock_balance = $stock - $qty;
$quantity = (int)$qty;
$db->query("UPDATE `inventory` SET `stock` = (`stock` - '$quantity') WHERE `item_name` = '$item_name'");
} else {
echo "<h3> This Operation Not Allowed: Stock Balance Is Less Than The Request <h3>";
}
First, unnecessary cast to integer, so remove line $quantity = (int)$qty; and put $stock_balance into query. We will have:
if ($stock >= $qty ) {
$stock_balance = $stock - $qty;
$db->query("UPDATE `inventory` SET `stock` = $stock_balance WHERE `item_name` = '$item_name'");
} else {
echo "<h3> This Operation Not Allowed: Stock Balance Is Less Than The Request <h3>";
}
...well... not only you are exhausted, so I will end now. Ask if something is not correct or not understandable.

php counter on mysql results

I got this simple foreach loop and can't figure out where is the problem with counter.
I get results like this. I am trying to make counter enlarged for one if it meets the conditions.
$building = 5;
$todaysdate = date("Y-m-d");
$tomorrows_date = date("Y-m-d", strtotime($todaysdate . "+1 days"));
$ends_date = "2018-04-30";
$counter = 0;
$query = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC"; // results give me numbers from 30 to 110.
$querydone = $db->query($query);
while($row = $querydone->fetch_assoc()) {
$every_id[$row['sifra']] = $row;
}
$firstday = new DateTime($tomorrows_date);
$lastday = new DateTime($ends_date);
for($q = $firstday; $q <= $lastday; $q->modify('+1 day')){
$result_day = $q->format("Y-m-d");
$i = 0; // counter for every value from mysql
foreach ($every_id as $key => $value) {
$counter = ${$i++} = $value['sifra'];
if($building >= $i) {
$valuesResult = "('$result_day','$counter')" . "<br />";
} else {
break;
}
echo $valuesResult;
}
}
Where am I wrong?
$building = 5;
$todaysdate = date("Y-m-d");
$tomorrows_date = date("Y-m-d", strtotime($todaysdate . "+1 days"));
$ends_date = "2018-04-30";
$counter = 0;
$query = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT 80"; // results give me numbers from 30 to 110.
$querydone = $db->query($query);
while($row = $querydone->fetch_assoc()) {
$every_id = $row['sifra'];
}
$firstday = new DateTime($tomorrows_date);
$lastday = new DateTime($ends_date);
for($q = $firstday; $q <= $lastday; $q->modify('+1 day')){
$result_day = $q->format("Y-m-d");
$i = 0; // counter for every value from mysql
foreach ($every_id as $key => $value) {
$counter = $i++;
if($building >= $i) {
$valuesResult = "('$result_day','$counter')" . "<br />";
} else {
break;
}
echo $valuesResult;
}
}

Use PHP while loop to create advance filter

I have a problem and that is I want to create a link on a website like people can click the link to show certain products only depending on percentage. like for example, i have a column in my database with discount percentage and it will show min discount and max discount. assuming we have min and max discount. $min=12 and $max=94; and I want to put them in links to show only products with certain discounts only like filtering. below is the example of the link.
<a href="#">12% to 20%</a
21% to 30%
31% to 40% and so on until it reaches
81% to 90% and the last will be
91% to 94%
smallest and largest numbers will be coming from a column from database and they can change frequently. i came up with solution and its working fine but my code is too long and its like I took to many steps which could be done in few lines of code. I have pasted my working code below but I am sure this can be reduced to few lines of code.
$catsql25 = "SELECT MAX(down_percentage) as largest FROM hot_deals";
$catquery25 = mysqli_query($conn, $catsql25);
while ($row25 = mysqli_fetch_array($catquery25, MYSQLI_ASSOC)){
$largest_number = $row25['largest'];
}
$catsql26 = "SELECT MIN(down_percentage) as smallest FROM hot_deals";
$catquery26 = mysqli_query($conn, $catsql26);
while ($row26 = mysqli_fetch_array($catquery26, MYSQLI_ASSOC)){
$smallest_number = $row26['smallest'];
}
$array_tens = array(10,20,30,40,50,60,70,80,90,100);
foreach ($array_tens as $value){
if(($value - $smallest_number <= 10) && ($value - $smallest_number > 0)){
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++){
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
}
foreach ($array_tens as $value2){
if(($largest_number - $value2 < 10) && ($largest_number - $value2 > 0)){
$lsst = $value2 + 1;
if($lsst != $largest_number){
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
}
elseif($lsst == $largest_number){
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
I know its all mess but..
Thanks.
First thing you could do is only one SQL Query :
$catsql = "SELECT MAX(down_percentage) as largest, MIN(down_percentage) as smallest FROM hot_deals";
And then you'll need only one loop :
$catquery = mysqli_query($conn, $catsql);
while ($row = mysqli_fetch_array($catquery, MYSQLI_ASSOC)){
$largest_number = $row['largest'];
$smallest_number = $row['smalest'];
}
After that, you could make only one foreach loop. The two "if" conditions could be in the same loop :
foreach ($array_tens as $value) {
if (($value - $smallest_number <= 10) && ($value - $smallest_number > 0)) {
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++) {
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
if (($largest_number - $value < 10) && ($largest_number - $value > 0)) {
$lsst = $value + 1;
if ($lsst != $largest_number) {
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
} elseif ($lsst == $largest_number) {
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
To make it more readable, you could also comment your code to know what do what.
This and a good indentation and you're right.
Hope it helps.

I dont know whats wrong in my code php If only 1 item in cart works properly but if many not working properly

My Code cant find the error on logic
I want the for loop to check if all quantity is avaiable before deducting it so i dont get negative quantity
if(isset($_POST['addtype'])){
$addedby;
$tchange;
$vatta;
$vatt;
$fdiscount;
$sum;
$cash;
$custname=$_POST['custname'];
$custadd=$_POST['custadd'];
$discount1=($fdiscount/100);
$salesdate=date("Y-m-d H:i:s");
$disc = ($sum * $discount1);
$discamount =($sum - $disc);
if($cash < $discamount){
echo "<script> alert('Please Input Cash!');</script>";
}
else{
$tchange = ($cash - $discamount);
$counter = 0;
$salesbarcode = null;
$salesquantity = null;
$sales = "SELECT * FROM salesitem WHERE transno='$transacnum'";
$squery =mysql_query($sales) or die ("ERROR".mysql_error());
while ($sarray = mysql_fetch_array($squery))
{
$salesbarcode[$counter] = $sarray['barcode'];
$salesquantity[$counter] = $sarray['quantity'];
$counter++;
}
This is my for loop so it will check if cart quantity < stock quantity
for ($i = 0; $i < $counter; $i++)
{
$salesbarcode[$i];
$salesquantity[$i];
$salebcode=$salesbarcode[$i];
$selectitem = "SELECT * FROM productinfo WHERE barcode='$salebcode'";
$stquery = mysql_query($selectitem) or die ("ERROR".mysql_error());
$strow = mysql_fetch_array($stquery);
$itemstock = $strow['qty'];
$itemname= $strow['prod_name'];
if($itemstock < $salesquantity[$i] )
{
echo "<script type='text/javascript'>alert('Insufficient Stock for Item $itemname')</script>";
echo "<script type='text/javascript'> window.location='pos1.php'</script>";
}
else{
$selectqty = "SELECT * FROM salesitem WHERE transno='$transacnum'";
$resultqty = mysql_query($selectqty) or trigger_error("SQL", E_USER_ERROR);
if ($resultqty)
{
$qty=0;
$count = 0;
$posbcode=null;
$posiqty=null;
$a=0;
while ($list = mysql_fetch_array($resultqty))
{
$posbcode[$count] = $list['barcode'] ;
$posiqty[$count] = $list['quantity'] ;
$count++;
}
for ($i = 0; $i < $count; $i++)
{
$posbcode[$i];
$posiqty[$i];
$pQty=$posiqty[$i] ;
$ino=$posbcode[$i];
$select="SELECT * from productinfo Where barcode='$ino'";
$res=mysql_query($select);
while($r=mysql_fetch_array($res))
{
$stkQty=$r['qty'];
$remQty= $stkQty-$pQty;
$update="UPDATE productinfo SET qty='$remQty' Where barcode='$ino'";
mysql_query($update) or die("Error: ".mysql_error());
}
}
}
$insert=mysql_query("INSERT INTO sales(salestransac ,salesdate,total,cash,discount,tchange,discamount,vatsales,vatamount,custname,custadd,AddedBy) VALUES ('$transacnum','$salesdate','$sum','$cash','$fdiscount','$tchange','$discamount','$vatt','$vatta','$custname','$custadd','$addedby')")or die (mysql_error());
if($insert){
echo "<script>alert('Transaction Complete!');window.location.href='posrec.php';</script>";}
}
you are using $i in your loop
for ($i = 0; $i < $counter; $i++) on line 1
and
for ($i = 0; $i < $count; $i++) on line 32
change the 2. one to $t for example

Add unique identifier to first iteration in PHP for loop

I am using a for loop on my client's website to insert purchased ticket information into a database. The loop is working correctly, but the client has requested the option to attach a unique identifier to the first entry every time the for loop is run. This identifier would be used to highlight the primary ticket owner when the tickets are printed. I have included the current for loop below for reference. Any ideas on how to achieve this? Thank you.
$threepack = '';
$i = '';
for($i = 0; $i < $tickets; $i++)
{
$firstname = 'firstname'.$threepack;
$lastname = 'lastname'.$threepack;
$address = 'address'.$threepack;
$city = 'city'.$threepack;
$postal = 'postal'.$threepack;
$phone = 'phone'.$threepack;
$altphone = 'altphone'.$threepack;
$sec_firstname = 'sec_firstname'.$threepack;
$sec_lastname = 'sec_lastname'.$threepack;
$email = 'email'.$threepack;
$table->firstname = $data->$firstname;
$table->lastname = $data->$lastname;
$table->address = $data->$address;
$table->city = $data->$city;
$table->postal = $data->$postal;
$table->phone = $data->$phone;
$table->altphone = $data->$altphone;
$table->sec_firstname = $data->$sec_firstname;
$table->sec_lastname = $data->$sec_lastname;
$table->email = $data->$email;
$table->id = 0;
$table->order_total = $data->total;
$table->store();
if($data->tickets == '-1')
{
if($threepack == 2)
{
$threepack = 3;
} else {
$threepack = 2;
}
}
// 8 Fields
if($data->tickets == '5')
{
if ($threepack == '') {
$threepack = 2;
} else {
$threepack += 1;
}
}
}
for ($i = 0; $i < $tickets; $i++) {
// ...
if ($i == 0)
$table->highlightme = 1;
// ...
$table->store();
// ...
}

Categories