How to calculate price? - php

Why doesn't my `$total' display any value when I run the code?

Initialize out side of the while loop
<?php
$total=0;
while ($row = ...
AND compute the $total as a running total inside ?PHP tag the echo it outside the loop to display the accumulated total
$total = $total + $row['price1'] + $row['price1'];

Try this,
<?php
$total=0;
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row["bookname"]; ?> </td>
<td><?php echo $row["price1"]; ?> </td>
<td><?php echo $row["cdname"]; ?> </td>
<td><?php echo $row["price2"]; ?> </td>
<td><?php echo $row["total"]; ?> </td>
</tr>
<?php $total = $total + $row['price1'] + $row['price2']; } ?>
Remember : $row['price1'] and $row['price2'] always be an integer values.

first you may want to put your total inside a php block then echo it

Initialize $total before the while loop. And after computation echo it outside the while loop.

Related

PHP totalling column and simplifying Sessions

I'm trying to total a column in a table of prices and it's not working out for me. I've looked at a ton of solutions such as array_sum() but it's not displaying anything for me. This is a cart page where I'm posting items to a session and then displaying in a for loop. I'm not sure if my sessions are overly complicated or what. Here is my session and post code:
session_start();
if( $_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['item'][] = array($_POST['item'], $_POST['price']);
}
?>
And here is my for loop section of code:
for($i=0; $i < count($_SESSION['item']); $i++){
$prices = $_SESSION['item'][$i][1];
$sum = 0;
$sum += $_SESSION['item'][$i][1];
print $sum;
?>
<tr>
<td class="left"> <?php print_r($_SESSION['item'][$i][0]) ?></td>
<td class="center"><?php echo "$ " . $_SESSION['item'][$i][1] ?></td>
</tr>
<?php
}
?>
<tr>
<td class="center">Total:</td>
<td></td>
</tr>
<?php
}
?>
</table><br>
Any help would be greatly appreciated!
Replace your current forloop with the following:
You were assigning $sum=0; inside loop so every time loop executed, your $sum variable would be assigned to zero and hence you would lose its value.
Sidenote: You should consider printing sum outside of loop.
$sum = 0;
for($i=0; $i < count($_SESSION['item']); $i++){
$prices = $_SESSION['item'][$i][1];
$sum += $_SESSION['item'][$i][1];
print $sum;
?>
At first your code must be like this:
$sum = 0;
for($i=0; $i < count($_SESSION['item']); $i++){
$prices = $_SESSION['item'][$i][1];
$sum += $prices;
?>
<tr>
<td class="left"> <?php print_r($_SESSION['item'][$i][0]) ?></td>
<td class="center"><?php echo "$ " . $_SESSION['item'][$i][1] ?></td>
</tr>
<?php
}
?>
<tr>
<td class="center">Total: <?=$sum?></td>
<td></td>
</tr>
<?php
}
?>
</table><br>
And the second if you want to sum column of prices from database then you can use mysql SUM function
Reference for mysql SUM

Can't get the value of a data PHP

im having trouble getting a result value of a query and the error says.
Notice: Undefined index: prelim in C:\xampp\htdocs\gradingxworking\teacher\student.php on line 85 can someone help me to fix this or some clue to fix this? im just starting to learn php.
<tbody>
<?php $c=1; ?>
<?php foreach($mystudent as $row): ?>
<tr>
<td><?php echo $c; ?></td>
<td class="text-center"><?php echo $row['studid']; ?></td>
<td class="text-center"><?php echo $row['lname'].', '.$row['fname']; ?></td>
<?php $grade = $student->getstudentgrade($row['studid']);?>
//code that cause error line 85--> <td class="text-center"><?php echo $grade['prelim']; ?></td>
</tr>
<?php $c++; ?>
<?php endforeach; ?>
<?php if(!$mystudent): ?>
<tr><td colspan="8" class="text-center text-danger"><strong>*** No Result ***</strong></td></tr>
<?php endif; ?>
</tbody>
the function:
function getstudentgrade($studid){
$q = "select * from studentsubject where studid=$studid";
$r = mysql_query($q);
$data = array();
while($row = mysql_fetch_array($r)){
$data[] = array(
'prelim' => $row['prelim']
);
}
return $data;
}
As #Bara suggested, you need to check the array first before accessing it.
if(isset($grade['prelim']))
I suspect, there is no data for specific studid. Lets see you function.
$data = array();
while($row = mysql_fetch_array($r)){
$data[] = array(
'prelim' => $row['prelim']
);
}
Now, you have created new array $data. But, if there is no record ? your while loop won't be executed and your $data array won't have anything. right ? So, to handle that, you need to check whether there is any data in your array.
Now, second point, which #Mossavari made is also correct. You need to use
$grade[0]['prelim'];
instead of
$grade['prelim'];
after doing
<?php $grade = $student->getstudentgrade($row['studid']);?>
you need to check what $grade holdes. and its better before trying to fetch data from array to make a check like this :
if(isset($grade['prelim']))
Based on your getstudentgrade function you'll have multidimensional array result, you may need to change $grade['prelim'] to $grade[0]['prelim']
Since, every student will have only 1 grade. So, why to use array.
<?php
function getstudentgrade($studid){
$q = "select * from studentsubject where studid=$studid LIMIT 0,1";
$data = "";
$r = mysql_query($q);
while($row = mysql_fetch_array($r)){
$data = $row['prelim'];
}
return $data;
}?>
PHP
<tbody>
<?php $c=1; ?>
<?php foreach($mystudent as $row): ?>
<tr>
<td><?php echo $c; ?></td>
<td class="text-center"><?php echo $row['studid']; ?></td>
<td class="text-center"><?php echo $row['lname'].', '.$row['fname']; ?></td>
<td class="text-center"><?php echo $grade = $student->getstudentgrade($row['studid']);?></td>
</tr>
<?php $c++; ?>
<?php endforeach; ?>
<?php if(!$mystudent): ?>
<tr>
<td colspan="8" class="text-center text-danger">
<strong>*** No Result ***</strong>
</td>
</tr>
<?php endif; ?>
</tbody>

For loop inside Foreach

I got a foreach which loops through my database for each user.
<?php
foreach($users as $user) {
?>
<tr>
<td>
<?php
for ($i=1; $i < 52; $i++) {
echo $i;
}
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
This loop through database and echos the username, now I tried to build a for loop inside this so that every user has a number, I took as an example a very basic for loop ( it will be changed later).
The problem is that I get all numbers printed out for each user, but I just want to print out the number once for a user. How do I solve this.
If you want unique index number for user, you do not need extra loop.
Just add an increment variable:
And increment it in existing loop.
<?php
$i=0;
foreach($users as $user) {
++$i; // For printing first user, it will be 1 not 0.
// Therefore, increment is placed before printing name.
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php
}
?>
This should be enough to achieve what you're trying to do :
Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it.
Also you should avoid to open your php tags ten thousands times for a better visibility into your code :)
<?php
$i = 0;
foreach($users as $user) {
$i++;
echo'<tr>
<td>'.$i.'</td>
<td>'.$user['firstname'].'</td>
</tr>';
?>
<?php
$i=1;
foreach($users as $user) {
?>
<tr>
<td>
<?php
echo $i++;
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
Try to use the key in foreach
<?php foreach ($users as $key => $user) : ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php endforeach; ?>

unique id for dynamic table

I will be generating a HTML table with data pulled from MySQL.The number of rows in my MySQL table are not fixed.
<?php
while($row=mysql_fetch_assoc($result))
{ ?>
<tr>
<td><?php echo $row['col1'];?></td>
<td><?php echo $row['col2'];?></td>
</tr>
<?php } ?>
Now how do I have the table rows and table data elements assigned unique id ??
Another loop to generate them won't work as I can't set an exit condition for the new loop as number of rows are not fixed.
Please guide me as to how to go forward about it. I can only use Javascript and not JQUERY.
Why can't you do something like this ?
<?php
$i = 1;
while($row=mysql_fetch_assoc($result))
{ ?>
<tr id="row<?php echo $i;?>">
<td id="cell-left-<?php echo $i;?>"><?php echo $row['col1'];?></td>
<td id="cell-right-<?php echo $i;?>"><?php echo $row['col2'];?></td>
</tr>
<?php
$i++;
} ?>
Please note, I have added ids row, cell-left- and cell-right- by myself. You may change them as per your requirements.
You can use a counter when iterating through the rows, maybe something like this:
<?php
$rowCount = 0;
while($row=mysql_fetch_assoc($result))
{
$rowCount++;
?>
<tr id="<?php echo 'row' . $rowCount;?>">
<td><?php echo $row['col1'];?></td>
<td><?php echo $row['col2'];?></td>
</tr>
<?php
}
?>
You can now select an element with
var rowID = 1;
document.getElementById("row" + rowID);
Hope this helps.

sum all value in foreach loop php

<?php foreach((array)$query as $row):?>
<td><?php echo $row->date ?></td>
<td><?php echo $row->cost ?></td>
<?php endforeach ;?>
I want to sum all values in $row->cost when $row->date=02-01-2016, like this in a table
Thanks.
echo array_sum(array_filter(array_map(function($row){
if($row->date == '02-01-2016')
return $row->cost;
}, $array)));
You can use
array_map: to compare and skip the values for which cost is not needed to add in sum.
array_filter: and then to remove the blank indexes
array_sum: and finally to sum cost
Note: if you are getting results from database, you can simply do sum there (see below):
$db->query("SELECT SUM(costs) FROM table_name WHERE `date`='2016-01-02'");
echo $db->fetchColumn();
Try below code:
<?php
$total = 0;
foreach((array)$query as $row):
$date = $row->date;
$cost = $row->cost;
if(date("M-d-Y", strtotime($date))==date("M-d-Y")) {
$total = $total+$cost;
}
?>
<td><?php echo $date ?></td>
<td><?php echo $cost ?></td>
<?php endforeach; ?>
<td colspan="2"><?php echo $total; ?></td>
<?php
$tot = 0;
foreach( (array)$query as $row ) {
if( $row->date=='02-01-2016' ) $tot = $tot+$row->cost;
?>
<tr>
<td><?php echo $row->date ?></td>
<td><?php echo $row->cost ?></td>
</tr>
<?php } ?>
<tr><td colspan="2"><?php echo $tot; ?></td></tr>
obviously, the comparison works if $row->date is formatted as dd-mm-yyyy
<table border=1>
<?php
$tot = 0;
foreach($query as $row ) {
if( $row->date=='2016-01-02' ) $tot += $row->cost;
?>
<tr>
<td><?php echo $row->date ?></td>
<td><?php echo $row->cost ?></td>
</tr>
<?php } ?>
<tr><td></td><td><?php echo $total; ?></td></tr>
</table>
It will work for you exctly what u want.

Categories