Multiplying values of select array two values from a POST array

Below i have an array from a select query that gives me the proper results

[php]<?php $sql = “SELECT categories, rate FROM lt_products WHERE categories IN (’”.implode("’,’",$pcategories)."’)
ORDER BY FIELD(categories, ‘".implode("’,’",$pcategories)."’)";
$result = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_assoc($result)) { ?>
<?php $row_duty = ($row["rate"] / 100);?>
<?php echo $row_duty?>

<?php } ?>

[/php]
if I echo $row_duty above expected values are correct

I also have the values from the post array that i am using a foreach loop to get the cost that should be multiplied by the above rate

[php]<?php foreach($ucost as $a => $b){ 		
	$duty = ($row_duty * $b);
	    echo $duty; ?><br>
<?php } ?>

[/php]
if i echo $b I get the expected right values, but when i try to multiply $row_duty * $b. The values are wrong.
It is multiplying each row in the for each loop only by the last row value in the select query.

Uncertain how to get proper values in each variable to get desired outcome
Help needed

Do this first:
[php]

<?php foreach($ucost as $a => $b): echo "

$a:$b

"; $duty = ($row_duty * $b); echo $duty; <?php endforeach; ?> [/php]

I’ve tried your suggestion but i am getting the results below.

if I put the for each before the select statement I get unknown variable $duty_row.

Based on the input the actual values of the duty column should look like this

Duty
25
70
135
160

<?php $sql = "SELECT `categories`, `rate` FROM `lt_products` WHERE `categories` IN ('".implode("','",$pcategories)."') ORDER BY FIELD(categories, '".implode("','",$pcategories)."')"; $result = mysql_query($sql)or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { ?>
						<?php $row_duty = ($row["rate"] / 100);?>
					
					
					<?php foreach($ucost as $a => $b): 	
							echo "<p>$a:$b</p>";
							$duty = ($row_duty * $b);
						 			echo $duty;
		 			endforeach; ?> 
					
				<?php } ?>			

This is the output from above

Duty

0:100

25
1:200

50
2:300

75
3:400

100
0:100

35
1:200

70
2:300

105
3:400

140
0:100

45
1:200

90
2:300

135
3:400

180
0:100

40
1:200

80
2:300

120
3:400

160

Well your logic is messed up, Igrooves…

You do a WHILE and then inside that you use ONE value from that and run a FOREACH inside of that. This will
not work. The solution would be to rethink your logic. So, your WHILE is based on a query. This query pulls
out categories and rates. Using a line like this: $row_duty = ($row[“rate”] / 100); This creates one and only
one $row_duty value. It changes each loop thru the WHILE clause. Instead, you should create an array of
both the category and the rate. Something loosely like:
$row_duty[] = $row[“category”] => $row[“rate”] / 100; (Not tested, just off top of my mind…)

Next, you would loop thru your FOREACH and in that loop do something like:
$duty = $row_duty[$a] * $b;

You can’t pull out one row of query data and then loop thru all of the items as they should change for each
of the rows of items. Or, another way would be to loop thru the FOREACH and run a query for each of the
items selecting only that one category. You would not need the WHILE in that case as the query would be
run for each of the $ucost items. One query for each $ucost would pull out one category rate. Either way!

Did that make sense? Hope it helps! Let us know after you think that out some…

Oh, why the complicated query? Do you have all of the product categories in an array in the database?
That is not normally how it would be done. But, that is another topic…

Hey Guys thanks, I haven’t tried it yet but i know I was having a problem with a part of the logic because running the query with the while loop for the rate separately and the foreach loop from the POST separately the values are correct the part i think I’m having the problem with, is trying to create the variables to do the calculations i need. I will try what you suggested

The answer to the Query question;

The categories and the rates are stored in a table called products, each category has a rate associated with it, but the costs and the categories are supplied by the user.

Then the rate for each category has to be found only based on the categories the user chooses. There are hundreds of categories in the database. once user inputs categories an the cost.

I now need to find the duty. The duty is actually a percentage rate of the cost

So final calculation i’m trying to achieve for each category selected is $duty = cost * Rate%

Well, just think out the logic…

Stored categories.
Stored rates (attached to categories)

User selects categories and enters the cost of them

Therefore, you need to parse thru the USER’s selection and run a query for each of them. usually, this would
cause a lot of queries. I would not do it that way. I would run one query to create an array of categories and
the corresponding rates. This makes the user-parsing faster as you just pull out the rate using the index of
the category. This will make it fast enough and simple. Your array for this would store a key that would be
the category number and the value that would be the rate. Then, you can just use that for your calculations.
One query and WHILE to load the array and one FOREACH to calculate the duty for each user’s category.

Did that make sense? Now, if you have 1000 categories, no big deal. If you have a million, then, you can
not create an array of that many. If there are a million categories, then you need to run a query for each of
the categories that the user selected. Of course, that number will be less than the million or thousand that
could be possible… Have to sort out the possibilities to decide which way to go.

Thanks Ernie,

I got my initial question to work after your suggestion made a little change to what you said, but its working now. I need now to SUM the value of that array but i can’t get it to work here’s what i have so far.

<?php $sql = "SELECT `categories`, `rate` FROM `lt_products` WHERE `categories` IN ('".implode("','",$pcategories)."') ORDER BY FIELD(categories, '".implode("','",$pcategories)."')"; $result = mysql_query($sql)or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { ?>
						<?php $row_duty[] =  $row["rate"] / 100; ?>
	  <?php } ?>
	  <?php 
			foreach($ucost as $a => $b): 	
					 $duty = $row_duty[$a] * $b;
						 {echo "$duty <br>";}
		 endforeach; 

	 ?>

    <?php $total_duty = array_sum($duty); ?> $<?php echo currency_display($total_duty);?>

I am getting this error message when I try to SUM the value.

Warning: array_sum() expects parameter 1 to be array, double given in C:\xampp\htdocs\customs\c17.php on line 638
$0.00

No problem, Igrooves! Glad to help…

You have two issues with your code. First, the error is because you didn’t stack the results from your ucost
loop. Lets go over it again so you understand it clearly. This is your current logic flow:

Stored categories.
Stored rates (attached to categories)

User selects categories and enters the cost of them
You loop thru these and create a SINGLE value of them called $duty which is category-cost*rate

Then, lastly you sum that one $duty item which is a single variable not a list of all of them.

NOW, I am sure you see the error there! You need to create an array of each cateory-cost*rate’s so that
you can sum the array, not one single item. (Which of course would be the last item in the first array!)
I think you get this from your changes in your last post…

So, the second problem is how you handle the overall logic of this project. If the data from both sections of
your code is pulled from the database, then, no problem. If the user’s categories and costs are pulled from
a form and posted to your PHP code, you have to make sure that the category matches the one you are
using to pull the rate for. Posted values are not always in order correctly. So, normally you would make sure
that the category matches the ones you are using from the database. That is why I suggested using a two
part array from the database and then compare the category before doing the computation as in my post.
If you are 100% sure that the ucost array is in the same EXACT order that the $duty array, then you are all
set.

Hey Ernie, Thanks for all your help,

I got everything to work, everything lines up calculations are coming out right

But now I’m getting a Notice: Undefined offset: 1 in C:\xampp\htdocs\customs\

This is only happening when a user inputs the same category twice on the input form which in some cases the user will need to input the same category more than once.

Example: User Input

Category Cost
Bicycles 320
Auto Parts 135
Bicycles 215

The reason a user would do this is that they may have bought the bicycles from two different stores so therefore need to input them as two different purchases.

when I check I am only getting the $rate for the first instance of bicycles and not the second

And the correct value for the $duty in the first instance of bicycles and 0 for in the second instance along with the Notice:

Below is the code that works if there are no duplicate entries. Any suggestions.

<?php $sql = "SELECT `categories`, `rate` FROM `lt_products` WHERE `categories` IN ('".implode("','",$pcategories)."') ORDER BY FIELD(categories, '".implode("','",$pcategories)."')"; $result = mysql_query($sql)or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { ?>
						<?php $row_duty[] =  $row["rate"] / 100; ?>
	  <?php } ?>
	  <?php 
			foreach($ucost as $a => $b): 	
					 $duty[] = $row_duty[$a] * $b;  //this is the line the notice is pointing to
		 	endforeach; 
			
		foreach($duty as $value){ 
			echo $value;?>  <br />
	<?php } ?>

Well, let’s go way back to the beginning. I told you that you would have that problem. In the database, you
have a list of categories. Only 1 entry for Bicycles! Therefore, if two are used in your user’s input, the order
will not match the user’s order. So, let’s say you have 100 categories. And, the user, enters the 3 you showed. (Query would pull 2 items, the foreach processes 3 items…)

The query pulls all 100 categories in order.
The user enters 2 categories in three lines.

There is no possible way that you can alter the query to handle that. That is exactly why I said to create an
array of the categories that you do in your query that holds both the key and value of each. So, instead of
doing something like:

<?php $row_duty[] = $row["rate"] / 100; ?>

You would need to do it like this:

<?php $row_duty[] = $row["categories"]=>($row["rate"] / 100); ?>

So, for example the if the first category was Bicycles, it would be entered as “Bicycles”=>rate…
I am not really sure what the data you are pulling looks like. Perhaps you should debug it and see what is
being sent to the loops. So, just before the foreach loop ( foreach($ucost as $a => $b): ) and this:
[php]
echo “
row-duty data:
”;
print_r($row_duty);
echo “
ucost data:
”;
print_r($ucost);
die(“done…”);
foreach($ucost as $a => $b):
[/php]
Then, enter as the user the same three you showed us 2-bicycles, 1 something else and see what is being
placed into each of your arrays. Post them and we can see what is failing. (After you fix that duty_row line)
Let us know…

When i replace this line

<?php $row_duty[] = $row["rate"] / 100; ?>

with this one

<?php $row_duty[] = $row["categories"]=>($row["rate"] / 100); ?>

I am getting the error below

Parse error: syntax error, unexpected ‘=>’ (T_DOUBLE_ARROW) in C:\xampp\htdocs\customs\c17.php on line 603

Didn’t know if this would help but if i leave it how it is and put in the echo statements that you sent this is what i’m getting with two bicycles in

row-duty data:
Array ( [0] => 0.35 [1] => 0.4 )
ucost data:
Array ( [0] => 187 [1] => 356 [2] => 256 ) done…

Very sorry, I was typing fast off the top of my head… Change this:

<?php $row_duty[] = $row["categories"]=>($row["rate"] / 100); ?>

To:

<?php $row_duty[$row["categories"]] = $row["rate"] / 100; ?>

(Again, sorry, I am coming off of two weeks of the flu!) That should change it up for you!

Sorry to hear about the Flu.

I changed the line to this

<?php $row_duty[$row["categories"]] = $row["rate"] / 100; ?>

and this is what is being echoed

row-duty data:
Array ( [Bicycles] => 0.35 [Televisions] => 0.25 )
ucost data:
Array ( [0] => 187 [1] => 435 [2] => 200 ) done…

And if i try to run the code with that line in it without the echo statement this is what im getting.

Notice: Undefined offset: 0 in C:\xampp\htdocs\customs\c17.php on line 609

Notice: Undefined offset: 1 in C:\xampp\htdocs\customs\c17.php on line 609

Notice: Undefined offset: 2 in C:\xampp\htdocs\customs\c17.php on line 609
0
0
0

Okay, so the first part is all set. You have an array of the categories with their values.

Now to fix the second part, you need to be able to pull out the category out of the $ucost…

It only uses an index, no category. How do you create the $ucost array? Can you show that part?
We must change it to store the category in the array instead of an index…

I am getting the $ucost array from the cost POST from the form.

$ucost=$_POST[‘cost’];

Well, that is not correct. First, if you have a $ucost array that is from POSTed data, you must have a way to
tell which category each of the cost items are attached to. What I mean is, you must have a row for each of
the categories that has the cost field for the user to enter. Therefore, you need to encode the array to show
them along with the costs. There are hundreds of ways to do that. Let’s discuss that part a bit so you do
clearly understand this issue…

Let’s say you have 10 items in your form for the user to enter costs into. They are normally listed with the
name of the category and a text field for the user to enter their cost into. You did not show us any of your
input form where the user enters costs. So, just guessing it might look loosely something like this:
Enter cost for Bicycles:
This would allow the user to enter the cost for Bicycles… So, when that is posted to the PHP code, it shows
up in the $_POST array something like “ucost”=>“what-they-type-in” … Now, normally, the way this would
be done is that the name would be the category name instead. Then, in the $_POST array, you would know
what categories are attached to what costs…

Without seeing your input form, I will guess you just lump in the costs without any indexes. Show us a bit
of your input form so we can see an example of your form where the user inputs one of the ucost values.

I am using javascript to intiate the other rows of the table. and then a query with a datalist for a drop down of options of categories as the user starts to type the category. this is the code below.

<?php //connect to mysql database $connection = mysqli_connect("localhost","root","","customs") or die("Error " . mysqli_error($connection)); //fetch data from database $sql = "select categories from lt_products"; $result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection)); ?>
        		<TD width="156"> <input name="pcategories[]" type="text" list="productcategories" class="input_field2" autocomplete="off" value="Description of Goods" id="pcategories" onfocus="clearText(this)" onblur="clearText(this)">
<datalist id="productcategories">
    		<?php while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ ?>
        		  <option value="<?php echo $row['categories']; ?>"><?php echo $row['categories']; ?></option>
    		<?php } ?>
					</datalist>
			<?php mysqli_close($connection); ?></TD>

$ucost=$_POST[‘cost’];

Use the code tags, that is what they are for.

Well, this partial line:
<input name=“pcategories[]”
Shows that you are placing all of your inputs into an array. But, you are forcing them to be UN-INDEXED!
To explain… The pcategories[] array is loaded with values that use an index key. But, the index is just the
standard 0,1,2,3, etc… And, that means there is no way to sequence them to tell them if they are in the same
order that matches the database query. One simple way to fix that would be to place the category into your
input array. So, to fix that you would need to change the way that you are indexing the pcategories array.
Basically, you can not do it the way you are handling it now.

Currently, you have the test user inputs in this format:
Bicycles 320
Auto Parts 135
Bicycles 215
This is done on screen by using a drop-down to capture the first part and a number input. To read this, you
would need to read both the categories from the drop-down’s and the cost numbers. You currently get the
ucost array like this:

I am getting the $ucost array from the cost POST from the form. $ucost=$_POST['cost'];
As you see, you are only getting numbers and not the matching categories. You would need to handle your posting in a better way!

Normally, if you have an input form that possibly has duplicated categories or duplicated parts, you would have
a numbered row of input lines. Then, you would use that row number as the array you would pull from the
posted data. In that pulled array, you would have the category used in each row and the cost of it. Then,
you would run the foreach on the numbered rows of input not on the categories themselves. Hope that
makes sense. You can not use a numeric index key without being able to tell one row from another when
the categories are the same. You will need to create a unique row number when you create your inputs.
You currently have no indexing ( <input name=“pcategories[]” ) You would need something in the index and
then assign the value to include both the category and the costs. Then, read in the values into an indexed
ucost array instead of an unindexed ucost array. Then, it is easy to do your calculations. One possible fix for
this process is to number each row. So, you can have a row number, 1,2,3 and assign the categories and the
costs using the row number attached. row#_category, row#_cost. Then read both into your ucost array.

Study on this a bit and ask your next question(s) on it…

Sponsor our Newsletter | Privacy Policy | Terms of Service