how to subtract two columns output in a third column using PHP - php

Using PHP I want to subtract each values of used column from credit column. I have created a tableA in phpmyadmin.
remaining:credit-used I can not get the results i just get same values of credit.
// The desire output in table A
id |date |credit |used|remaining|
1 |20-5-2013 |400 |300 |100 |
2 |19-5-2013 |300 |100 |200 |
3 |18-5-2013 |600 |50 |550 |
// db connection
query select all from tableA
$sql = "SELECT * FROM tableA";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
?>
fetch the information and output into a table:
<table >
<tr>
bla bla..
</tr>
// echo:
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["date"]; ?></td>
<td><?php echo $row["credit"]; ?></td>
<td><?php echo $row["used"]; ?></td>
I'm trying to do this query to get remaining:
// <td> <?php> echo $total= $row["credit"] - $row["used"];?>
</td>
</tr>
</table>
can anyone give me a hints or highlight the error. Than you very much in advance.

What you have should work, but why not let MySQL do the calculation?
mysql_query("SELECT *, `credit`-`used` AS `remaining` FROM `tableA`");

You have a closing bracket on your php
<td> <?php echo $row["credit"] - $row["used"]; ?> </td>

Related

PHP and Mysql with INNER JOIN query - only seeing headers, no data

<?php
$conn = mysqli_connect("localhost", "root", "", "konkal");
$result = mysqli_query($conn,"
SELECT *
FROM tb_hitung
JOIN tb_makanan
ON tb_hitung.id = tb_makanan.id
WHERE ket_waktu = 'pagi'
");
while( $row = mysqli_fetch_assoc($result));
?>
<tr>
<th>Gambar Makanan</th>
<th>Nama Makanan</th>
<th>Jenis Makanan</th>
<th>Waktu Makan</th>
<th>Jumlah Kalori</th>
</tr>
<tr>
<td><img src="<?php echo $row['gambar'] ?>" width="100"></td>
<td><?php echo $row["nama"] ?></td>
<td><?php echo $row["kategori"] ?></td>
<td><?php echo $row["ket_waktu"] ?></td>
<td><?php echo $row["kkal"]," kkal" ?></td>
</tr>
Table tb_hitung:
id kkal ket_waktu
12 360 kkal pagi
2 810 kkal malam
24 108 kkal siang
9 286 kkal pagi
Table tb_makanan:
id name kategori keterangan gambar
2 Ampela Lauk 270 Amepela.jpg
3 Usus Lauk 473 Usus
4 Bebek Lauk 300 Bebek
I expect the output to display results where the query filters ket_waktu = 'pagi'. I am only seeing the first row of table (the headers).
PART 1
Join point tb_hitung.id = tb_makanan.id only creates one "match".
For example: tb_hitung id 12 should match to tb_makanan id 12. but tb_makanan has ZERO ROWS with id 12 (no match).
There is a single match...it is on hitung 2 and makanan 2...but the where clause filters to hitung of "pagi". So given this data, the query will have ZERO ROWS.
PART 2
As #barmar mentions...the semicolon ends your while loop without ever looping and the header row should not be within what appears to be your loop. I'll clarify all this chit-chat with one example of an appropriate loop for this purpose:
<?php
$conn = mysqli_connect("localhost", "*******", "", "*******");
// keep your query in a variable for quick debugging
$query = "SELECT * FROM tb_hitung JOIN tb_makanan ON tb_hitung.id = tb_makanan.id";
// i removed the WHERE clause since it was filtering all rows
$result = mysqli_query($conn, $query);
// print your header row OUTSIDE the loop
?>
<tr><th>Gambar</th><th>Nama</th><th>Jenis</th><th>Waktu</th><th>Jumlah</th></tr>
<?php
// now do the loop of the data...
// WHILE should open with an OPENING BRACKET (not end with a semicolon)
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><img src="<?php echo $row['gambar'] ?>" width="100"></td>
<td><?php echo $row["nama"] ?></td>
<td><?php echo $row["kategori"] ?></td>
<td><?php echo $row["ket_waktu"] ?></td>
<td><?php echo $row["kkal"]," kkal" ?></td>
</tr>
<?php
// now we must END THE WHILE LOOP
}

Could not get sum of each row in a column in php mysql table

enter image description hereenter image description hereI have a database table having multiple cols and data in many rows. I want to get sum of all data of all the data in each row and place in a col 'Total'. However, Grand total is showing in each row and not the total of each row.
I am presenting the code as below
<?php
include 'config.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$add=mysqli_query($con,"SELECT Col1, Col2, Col3, Col4,
sum(Col1 + Col2 + Col3 + Col4) AS Total, SUM(Col1), SUM(Col2),
SUM(Col3), SUM(Col4)
from DistrictData WHERE District = 'District1' ");
while($row=mysqli_fetch_array($add))
{
$Total = $row['Total'];
$SUM1=$row['SUM(Col1)'];
$SUM2=$row['SUM(Col2)'];
$SUM3=$row['SUM(Col3)'];
$SUM4=$row['SUM(Col4)'];
$Total2= $SUM1 + $SUM2+ $SUM3+ $SUM4 ;
}
}
$sql="SELECT * FROM DistrictData WHERE District = 'District1'"; $counter = 0;
$result = $con->query($sql);
?>
<body>
<table >
<tr>
<td>Sr No.</td>
<td>Deptt</td>
<td>Data Description</td>
<td>Unit</td>
<td>Year</td>
<td>Blocks in District</td>
</tr>
<tr>
<td>Total</td>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
<td>Col4</td>
</tr>
<?php
while($rows = $result->fetch_assoc())
{
?>
<tr>
<td><?php echo ++$counter; ?></td>
<td><?php echo $rows['Data']; ?></td>
<td><?php echo $rows['Description']; ?></td>
<td><?php echo $rows['Unit']; ?></td>
<td><?php echo $rows['Year']; ?></td>
<td> <?php echo $Total ?></td>
<td><?php echo $rows['Col1']; ?></td>
<td><?php echo $rows['Col2']; ?></td>
<td><?php echo $rows['Col3']; ?></td>
<td><?php echo $rows['Col4']; ?></td>
</tr>
<?php
}
?>
<tr>
<td>Total:</td>
<td> <?php echo $Total2 ?></td>
<td> <?php echo $SUM1 ?></td>
<td> <?php echo $SUM2 ?></td>
<td> <?php echo $SUM3 ?></td>
<td> <?php echo $SUM4 ?></td>
</tr>
</table>
<?php
$con->close();
?>
Output of the code
Please suggest any changes in the code so that I could get the sum for each row in Total Column.
Thanks in advance
Use this query for row sum of column elements
SELECT Col1+Col2+Col3+Col4 as I_want_this_figure from DistrictData
Note that a normalised environment would typically look more like this...
sr_no district_block val
1 1 5
1 2 6
1 3 5
1 4 8
2 1 226
2 2 112
2 3 4
2 4 5
3 1 2
3 2 7
3 3 3
3 4 8
... where (sr_no,district_block) are components of a PRIMARY KEY
Use Allies after every Sum() as something.
You will get last result when you take away total from while loop.
do your first Query under 2nd Query and pass the ID as parameter.
while($row = mysqli_fetch_array($query)){
$total_query = mysqli_query($con,"SELECT Col1, Col2, Col3, Col4,
SUM(Col1 + Col2 + Col3 + Col4) as Total from DistrictData WHERE id='row[yourID]'");
$total_result = mysqli_fetch_array($total_query);
NOW you can populate your data here
}
Hope this will help you.

How to write Orderby Clause with where with where clause to sort data

hi i'm trying sort mysql data in table but my problem is that my query is sorting all the data my table looks like
Word | Meaning | Synonym | Antonym
definitely | without doubt | certainly |possibly
great | of an extent, amount | considerable |little
zeal | great energy | passion | indiference
zealot | a person who is fanatical|fanatic | moderate
zealous | having or showing zeal. | fervent | apathetic
so when i search lets say word starting wit z then i get
Word | Meaning | Synonym | Antonym
zeal | great energy | passion | indiference
zealot | a person who is fanatical|fanatic | moderate
zealous | having or showing zeal. | fervent | apathetic
now i want to perform sorting on these searched data but my sort query is sorting the all data
my store procedure looks like
CREATE DEFINER=`root`#`localhost` PROCEDURE `SortContent`()
BEGIN
SELECT * from dictionarysearch ORDER BY word ASC;
END
and my php code is like
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here i'm calling a function which is calling the store procedure
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><i class="fa fa-edit"></i> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
</table>
so i want to know how i can write a query so that it sorts only selected data and i have set id autoincrement
There is no need to use a stored Procedure for this. I suggest that the following code will work for you...
<?php
if(isset($_GET['search_btn']) && strlen($_GET['search'])){
$search = mysqli_escape_string($conn,$_GET['search']);
$sql = "SELECT * FROM dummydata WHERE info LIKE '".$search."%'";
if(isset($_GET['sort']) && in_array($_GET['sort'], array('ASC', 'DESC'))){
$sort=$_GET['sort'];
$sql .= " ORDER BY info ".$sort;
}
//echo "<h3>".$sql."</h3>";
if (($result=mysqli_query($conn,$sql))!==false) {
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<tbody>
<?php
while ($row=mysqli_fetch_assoc($result)){
//echo "<pre>".var_export($row,true)."</pre>";
?>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td>Your action url here.... </td>
</tr>
<?php } ?>
</tbody>
</table>
<?php
} else {
echo "<h3>Problem with SQL</h3>";
}
}
?>
I hope that this helps.

how do i print data vertically using loops

I have following problem .
I print data from a table name exam having student_id and marks_obtained for each student_id and. My output is as follow
but i want the table in different format
-----------------------
subject | marks | total
-----------------------
toward down side
as this see output
but am confused in code please help me
my CODE IS FOLLOW:
$roll=$_POST['roll'];
$exam=$_POST['exam'];
$int1 = intval(preg_replace('/[^0-9]+/', '', $exam), 10);
$student_info="select student_id,name,father_name,mother_name,roll,class_id,birthday,parent_id from student where roll='$roll'";
$result_student=mysqli_query($link, $student_info) OR trigger_error('login info error');
$data_student= mysqli_fetch_array($result_student,MYSQL_BOTH);
$parent_info="select name from parent where parent_id='$studentparent'";
$result_parent=mysqli_query($link, $parent_info) OR trigger_error('login info error');
$data_parent= mysqli_fetch_array($result_parent,MYSQL_BOTH);
$parentname= $data_parent['name'];
$subject_info="select subject_id,name from subject where class_id='$studentclass'";
$result_subject=mysqli_query($link, $subject_info) OR trigger_error('login info error');
$data_subject= mysqli_fetch_array($result_subject,MYSQL_BOTH);
<table>
<tr>
<td> Subject </td>
<td> Marks </td>
<td> Total </td>
</tr>
<tr>
<?php
for($i=0;i<count($data);i++){
?>
<td><?php echo $data['subject_name'];?></td>
<td><?php echo $data['marks'];?></td>
<td><?php echo $data['total'];?></td>
<?php
}
</tr>
</table>

How to make order history to online shop in php?

Problems:
1) Just 3 id_penjualan rows were displayed in order history, it should be 4 id_penjualan rows.
2) jumlah and total have same value, it should be different for each other depending on sum of product quantity of each transaction.
Table tb_penjualan:
Table: tb_detail_penjualan:
Output:
Code:
<?php
$id_pelanggan=$_SESSION['user_session'];
$query="SELECT tb_penjualan.*, tb_pelanggan.nama_dpn, tb_pelanggan.nama_blk
FROM tb_penjualan LEFT JOIN tb_pelanggan
ON tb_penjualan.id_pelanggan=tb_pelanggan.id_pelanggan
WHERE tb_penjualan.id_pelanggan=:id_pelanggan
AND tb_penjualan.checkout='yes' ORDER BY id_penjualan";
$stmt=$con->prepare($query);
$stmt->execute(array(":id_pelanggan"=>$id_pelanggan));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$id_penjualan=$row['id_penjualan'];
if($stmt->rowCount()>0)
{
$query2="SELECT SUM(subtotal) AS total, SUM(jumlah) as total_jml
FROM tb_detail_penjualan
WHERE id_penjualan=:id_penjualan";
$stmt2=$con->prepare($query2);
$stmt2->execute(array(":id_penjualan"=>$id_penjualan));
$stmt2->execute();
$row2=$stmt2->fetch(PDO::FETCH_ASSOC);
$no=1;
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{?>
<tr>
<td></td>
<td><?php echo $no++;?></td>
<td> <?php echo $row['id_penjualan'] ;?></td>
<td><?php echo $row['nama_dpn'] ;?> <?php echo $row['nama_blk'] ;?> </td>
<td><?php echo date('d F y', strtotime($row['tanggal_blj'])); ?></td>
<td><?php echo $row2['total_jml']; ?></td>
<td> <?php $harga = $row2['total'] ?> <?php echo "Rp. " .number_format($harga, 0, ',', '.');?></td>
<td>Rp. </td>
<td></td>
</tr>
<?php
}
} else { ?>
<p>Order history empty</p>
<?php }?>
</tbody>
You have 2 queries in your code:
$query executed with $stmt
$query2 executed with $stmt2 and you fetch first row in $row2.
Then you have a loop, where you are fetching all rows from $stmt via variable $row. So $row contains each time values from next row of the first query.
But inside the loop you are also outputting information from $row2, which doesn't change (it is still the first row fetched before the loop), so each time it prints the same output.

Categories