I have an index.php with various SQL queries which helps me find the balances of the respective accounts. This is a TRIAL BALANCE so I need to SUM all the amount in the Debit Column and SUM all the amount in the Credit Column so that I can Tally both of them. Please help me with the SUM. All values are echoed to a PHP table.
index.php
<?php
echo "<table border='1'>";
echo "<tr><th width='150'>Account</th><th width='200'>Debit</th><th width='200'>Credit</th></tr>";
echo "<tr><th align='left'>Cash & Bank</th></tr>";
//List the Banks first with their respective balances.
$bank_sql = "SELECT * FROM bank";
$bank_query = mysqli_query($conn, $bank_sql);
while ($bank_result = mysqli_fetch_array($bank_query)){
$bank_name = $bank_result['name'];
$sql= "SELECT SUM(amount) FROM account WHERE (mode='$bank_name' AND status='completed') AND (type='p' OR type='r')";
$sql_query = mysqli_query($conn, $sql);
while($sql_result = mysqli_fetch_array($sql_query)){
$sql_value = $sql_result['SUM(amount)'];
}
$sql1 = "SELECT SUM(amount) FROM account WHERE (mode='$bank_name' AND status='completed') AND (type='s' OR type='pa')";
$sql1_query = mysqli_query($conn, $sql1);
while($sql1_result = mysqli_fetch_array($sql1_query)){
$sql1_value = $sql1_result['SUM(amount)'];
}
echo "<tr><td>".$bank_name."</td>";
if ($sql_value > $sql1_value){
echo "<td align='right'>AED " . number_format(($sql_value - $sql1_value),2) . "</td><td> </td>";
}
elseif ($sql1_value > $sql_value) {
echo "<td> </td><td align='right'>AED " . number_format(($sql1_value - $sql_value),2) . "</td>";
}
else {
echo "<td> </td><td> </td>";
}
}
echo "</tr></table>";
}
?>
Try the below query
SELECT SUM(amount) FROM ht_account WHERE mode='$bank_name' AND status='completed' AND type IN('sale','purchase','reciept','payment')
A quick way to do it would be.
$sql3="select column1,column2 from yourtable where ..condition";
$sumofcolumn1;
$sumofcolumn2;
while($sql3_result = mysqli_fetch_array($sql3))
{
$sumofcolumn2+=$sql3_result['column2'];
$sumofcolumn1+=$sql3_result['column1'];
}
echo $sumofcolumn1.' '.$sumofcolumn2
Related
I have a table in a database and am currently pulling data using the SELECT statement Where the information from the column Opinion equals either Negative or Positive.
what i want to also do is output the positive data as an overall percentage but Unsure if that would be possible i had a look at multiple overflow questions but couldn't see anything. Any help would be appreciated.
$sql = "select Opinion from survey where Opinion = 'Positive'";
$result = mysqli_query($con, $sql);
if (!$result) {
die(mysqli_error($con));
}
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Date</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
}
} else {
echo "0 results";
}
?>
The query will calculate how many percentage of 'Positive' opinions compared to total rows of the 'survey' table:
select (SUM(IF(Opinion = 'Positive',1,0))/count(*))*100 as percentage_positive
from survey
The query below can determine the percentage of each different opinions at once:
select
Opinion,
count(*) as total,
(count(*) / (select count(*) from survey))*100 as percentage
from survey
group by opinion
Something like this as SQL query?
SELECT COUNT(Opinion) / (SELECT COUNT(Opinion) FROM survey) * 100
FROM survey
WHERE Opinion = 'Negative'
After help from Kevin HR i have fixed my issue with the code below.
$sql = "select Opinion,count(*) as total,(count(*) / (select count(*) from survey))*100 as percentage from survey group by opinion";
$result = mysqli_query($con, $sql);
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Percentage</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
echo "<td>" . $row['percentage'] . "</td>";
}
}
else {
echo "0 results";
}
Working code for getting the value of number of rows from a database
$sql = "SELECT * FROM `survey` WHERE Opinion='Positive'";
$connStatus = $con->query($sql);
$numberOfRows = mysqli_num_rows($connStatus);
echo "There are a total number of $numberOfRows Positive rows in the database";
echo "<br>";
echo "<br>";
I'm trying to display information from two queries in one single table, but can't figure out how to make it work.
This is what I got working with one query:
SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;
Company Employees
ABC 45
DEF 15
GHI 5
Now beneath that I'd like to have another query that simply counts all rows, giving me the total amount of Employees.
SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;
SELECT COUNT(*) AS Total FROM Employee_Table;
Company Employees
ABC 40
DEF 15
GHI 5
Total 60
This is what my code looks like right now. I defined two extra variables for my extra query that I want to echo out, but believe this is not the proper way to do it as I get an sqlsrv_fetch_array error.
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$query2 = "SELECT COUNT(*) AS Totaal FROM Employee_Table;";
$result1 = sqlsrv_query($conn, $query1);
$result2 = sqlsrv_query($conn, $query2);
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=sqlsrv_fetch_array($result1, $result2)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
echo "</td><td>";
echo $row["Total"];
echo "</td></tr>";
}
echo "</table>";
How can this be achieved? I'd appreciate any help
First correct
sqlsrv_fetch_array()
see here http://php.net/manual/de/function.sqlsrv-fetch-array.php
Use just a single query and use mysqli_num_rows() function to count
$count = mysqli_num_rows($result);
I think you can achieve this by using only first query
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$result1 = mysql_query($conn, $query1);
$total_employee = 0;
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=mysql_fetch_array($result1)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
$total_employee += $row["count"];
echo "</td><td>";
echo "</td></tr>";
}
echo "<tr><td>Total</td><td>$total_employee</td></tr>";
echo "</table>";
You can use only one query:
$result = sqlsrv_query($conn, "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC");
?>
<table id='total'>
<tr><th>Company</th><th>Amount of employees</th></tr>
<?php
$total = 0;
while ($row=sqlsrv_fetch_array($result)) {
$total += $row["count"];
?>
<tr><td><?= $row["Company"] ?></td><td><?= $row["count"] ?></td></tr>
<?php
}
?>
<tr><td></td><td><?= $total ?></td></tr>
</table>
<?php
Try the following code
$query1 = "SELECT Company,COUNT(*) as count FROM Employee_Table GROUP BY Company ORDER BY count DESC;";
$query2 = "SELECT COUNT(*) AS Totaal FROM Employee_Table;";
$result1 = sqlsrv_query($conn, $query1);
$result2 = sqlsrv_query($conn, $query2);
echo "<table id='total'>";
echo "<tr><th>Company</th><th>Amount of employees</th></tr>";
while ($row=sqlsrv_fetch_array($result1)) {
echo "<tr><td>";
echo $row["Company"];
echo "</td><td>";
echo $row["count"];
echo "</td><td>";
echo "</td></tr>";
}
$rows = sqlsrv_fetch_array($result1)
echo "<tr><td>";
echo $rows["Total"];
echo "</td></tr>";
echo "</table>";
I have had a long road to get to this last question. Everything is my code is working now, but I can't get this last little issue. Right now I have:
$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS
value_sum FROM maindata GROUP BY phonenumber, dataplan";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$val = $row["value_sum"];
$plan = $row["currentplan"];
$remain = $plan - $val;
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
It only subtracts the first value as opposed to the values for all. displayed like this:
while ($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['phonenumber'] . "</td> ";
echo "<td>".$row['currentplan'] . "</td> ";
echo "<td>".ROUND ($row["value_sum"],2) . "MB</td> ";
echo "<td>".$remain . " MB</td> ";
echo "<td>".$row['email'] . "</td></tr>";
}
So my goal is to subtract all value_sums from all dataplans, but what I have now, gives me the first value for all columns. Thank you!
mysql_fetch_assoc() will always get one row. You can use it in loop, or better use PDO, eg. like this:
$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS
value_sum FROM maindata GROUP BY phonenumber, dataplan";
$results = $pdo->query($sql);
You can read about creating PDO connections here http://www.php.net/manual/en/book.pdo.php
Thanks for reading my question
i am trying to make *clients_id* from the table repair_jobs appear as the name from the table contacts
but i am having no luck
i have got 2 sql query's is this wrong?
the 1st
$query = "select * from repair_jobs";
this helps me display the information i need regarding the fields from repair_jobs and works
this is the 2nd
$query = "SELECT repair_jobs.client_id, contacts.name
FROM repair_jobs
INNER JOIN contacts
ON repair_jobs.client_id=contacts.name";
under that i have this to try to display the name of the client
echo "<td>{$client_id}</td>";
but it is only displaying the number and not the data (clients name) that i need
am i missing something?
Additional information
The client_id (repair_jobs) is a number and is the same as id (contacts) but wanting to display the name (contacts)
CLIENTS
Id – name – surname – phone – address
REPAIRS
Id – clients_id (same as id in clients) – unit – date – price
current code
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = "select * from repair_jobs";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database record
//start table
//creating our table heading
echo " <table class='table_basic'>";
echo "<thead><tr>";
echo "<th>Job #</th>";
echo "<th>Name Of Unit</th>";
echo "<th>Client</th>";
echo "<th>Estimated Value</th>";
echo "</thead></tr><tbody><tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td width='40px'><a href='rdetails.php?id={$id}'># {$id}</a></td>";
echo "<td>{$rmake} {$rmodel}</td>";
$query = "SELECT rj.client_id, c.name AS client_name FROM repair_jobs rj INNER JOIN contacts c ON rj.client_id=c.id";
echo "<td>{$client_name}</td>";
echo '<td align="center"><span class="badge badge-success">£';
$lhours = $labour;
$repaircosts = $ourcosts;
$labourpay = $labourcharge;
$sum_total = $repaircosts +($lhours * $labourpay);
print ($sum_total);
echo '</span></td>';
echo "</td>";
echo "";
}
echo "</tr></table>";//end table
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
Change your 1st query to you join query, as there is no reason to do a 2nd query in the middle of your code. (also you never executed that query anyway).
//query all records from the database
$query = "SELECT repair_jobs.*, contacts.name as client_name
FROM repair_jobs
INNER JOIN contacts
ON repair_jobs.client_id=contacts.id";
Then in your table keep the $client_name
echo "<td>{$client_name}</td>";
<?php
include 'db_connect.php';
$query = "SELECT rj.Id AS job_number, rj.unit, rj.make, rj.model, c.name AS client_name, rj.price FROM repair_jobs rj INNER JOIN contacts c ON rj.clients_id = c.id ORDER BY c.date";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
if( $num_results > 0){ //it means there's already a database record
echo " <table class='table_basic'>";
echo "<thead><tr>";
echo "<th>Job #</th>";
echo "<th>Name Of Unit</th>";
echo "<th>Client</th>";
echo "<th>Estimated Value</th>";
echo "</tr></thead><tbody>";
while( $row = $result->fetch_assoc() ){
extract($row);
echo "<tr>";
echo "<td width='40px'><a href='rdetails.php?id={$job_number}'>#{$job_number}</a></td>";
echo "<td>{$make} {$model}</td>";
echo "<td>{$client_name}</td>";
echo "<td align='center'><span class='badge badge-success'>£";
$lhours = $labour;
$repaircosts = $ourcosts;
$labourpay = $labourcharge;
$sum_total = $repaircosts +($lhours * $labourpay);
echo $sum_total;
echo '</span></td>';
echo "</td>";
echo "</tr>";
}
echo "</tbody></table>";
} else {
echo "No records found.";
}
$result->free();
$mysqli->close();
?>
I have a inner join statment which is working 90% as it is displaying what I need it to display but unfortunately it is not displaying to the right user logged in. It is being displayed to whoever logs into my system. Here is the code:
<?php
$result = mysql_query("SELECT * FROM Agendas INNER JOIN Meetings ON Meetings.secretary WHERE Agendas.approval = 'disapproved' AND secretary = '". $_SESSION['username']."'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'You Have No New Messages';
} else {
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><br/>" .'Title: '. $info['title']." </td>";
echo "<td><br/>" .'Approved: '. $info['approval']. "</td>";
echo "<td><br/>" .'Reason: '. $info['reason']."</td>";
echo "<hr>";
}
}
echo "</tr>";
echo "</table>";
?>
my database tables look like this:
Meetings: meeting_id, title, chairperson, secretary, tof, occurances, action
Agendas: agenda_id, subject, duration, meeting_id, approval, reason.
thanks soo much for any help :)
i think you're doing something wrong in the join clause. how about this:
$result = mysql_query("SELECT * FROM Agendas INNER JOIN Meetings ON Agendas.meeting_id = Meetings.meeting_id WHERE Agendas.approval = 'disapproved' AND secretary = '". $_SESSION['username']."'")
or die(mysql_error());