Select two columns and take their count - php

I making one table, and i want to make table ordered by desc,
Example: Take Bank_Account + HandMoney = SUM, and write the sum of that by the Desc
I alredy maked Table by only "HandMoney" and it works good, but i realy dont know how to make sum of two columns
Code what i have now:
$query = $connection -> prepare("SELECT `p_name`, `HandMoney` FROM `users` ORDER BY `HandMoney` DESC LIMIT 15");
if($query -> execute())
{
if($query -> rowCount())
{
$count = 0;
?>
<thead>
<table class="table-fill2">
<tbody class="table-hover">
<tr>
<th class="text-left">
Postion
</th>
<th class="text-left">
Player Name
</th>
<th class="text-left">
Money
</th>
</tr>
</thead>
<tbody class="table-hover">
<?php
while($query_result = $query -> fetch())
{
?>
<tr>
<td style = "text-left">
<?php
echo ++ $count;
?>
</td>
<td style = "text-left">
<?php
echo $query_result['p_name'];
?>
</td>
<td style = "text-left">
<?php
echo number_format($query_result['HandMoney']);
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
else
{
echo 'No players were found.';
}
}
?>
So i want take two columns (HandMoney + BankMoney = SUM) and order player by that sums

If i understand right you want to have that:
SELECT `p_name`, SUM(Bank_Account + HandMoney) as BandH
FROM `users`
GROUP BY p_name
ORDER BY BandH DESC

Related

Display only specific data from array containing database values

I have a query which select the last entered data into the database month wise and i have assigned it into an array and tried to display it inside a table which works fine but the data is combined togeather as shown below
Example - the first numeric data you see on the table 1245871 should be displayed as follows
Month - 12
Closing Mileage - 45871
But as you can see on the image both the data are combined togeather how can i seperate these two values and display them accordingingly. The code for this is as below,
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$querymain = "SELECT * FROM users";
$resultsmain = mysqli_query($connect,$querymain);
if ($resultsmain->num_rows>0) {
while ($userid = mysqli_fetch_assoc($resultsmain)) {
?>
<table class="table" class="mt-3 mb-3">
<thead class="bg-dark text-light">
<tr>
<th colspan="3"><?php echo $userid['id']; ?></th>
<th colspan="3"><?php echo $userid['name']; ?></th>
<th colspan="3"><?php echo $userid['approved_kmpl'];?> KM</th>
</tr>
</thead>
<thead>
<tr>
<th>Month</th>
<th>Closing Mileage</th>
<th>Usage For Month</th>
<th>Required Per Month</th>
<th>Excess Used</th>
<th>(%)</th>
<th>KM/L</th>
<th>Consumed Liters</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<?php
$closingmileage = "SELECT extract(MONTH from date) as Month,
MAX(mileage) FROM mileagesnew
WHERE user_id='".$userid['id']."'
AND extract(YEAR FROM date) ='2020'
group by Month
ORDER BY month desc";
$closingres = mysqli_query($connect,$closingmileage);
if ($closingres->num_rows>0) {
while ($closingrow = mysqli_fetch_assoc($closingres)) {
$data =array($closingrow);
foreach($data as $value){
print_r($value);
?>
<tr>
<td> <?php echo implode($value); ?> </td>
</tr>
<tr>
<td> <?php echo implode($value); ?> </td>
</tr>
<?php
}
}
}
else{
echo "No Data Found";
}
?>
</tbody>
</table>
<?php
}
}
You have 2 columns returned in the resultset of the query Month and mileagesnew. So $closingrow will be an array with 2 members, named as the columns names from your table, or the alias you give the column name in the query. So all you need to do is output $closingrow['Month'] and $closingrow['mileagesnew'] seperately in the 2 table cells
Also I assume you want the 2 values on the same row of the tabel to output both cells within the same <tr>...</tr> along with the empty cells you have not filled yet
<?php
$closingmileage = "SELECT extract(MONTH from date) as Month,
MAX(mileage) FROM mileagesnew
WHERE user_id='".$userid['id']."'
AND extract(YEAR FROM date) ='2020'
group by Month
ORDER BY month desc";
$closingres = mysqli_query($connect,$closingmileage);
if ($closingres->num_rows>0) {
while ($closingrow = mysqli_fetch_assoc($closingres)) {
echo "<tr>
<td>$closingrow[Month]}</td>
<td>$closingrow[mileagesnew ]</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>";
}
} else{
echo "No Data Found";
}
?>

Change td content according to database

I have two table for assignments. TABLE1 has the data of the assignments posted by a faculty and TABLE2 has data of those students who submitted the assignments. Both table have one similar column called 'assignment name'.
My TABLE2 has a status column which is boolean data. By default i have set it to 0 and if a student submit his assignment that changes to 1.
In my HTML page (student side) I'm displaying the data from TABLE1 in a table. It shows all assignments name and I have given a submit status column there which will show if the assignment work is submitted by the logged in student. If yes it will show a check icon if not then a times icon.
This is what i have tried:
<?php
session_start();
include'connection.php';
$user=$_SESSION['details1'];
$query =mysqli_query($con,"SELECT course FROM student WHERE username='$user'");
while($row=mysqli_fetch_array($query))
{
$cr=$row['course'];
}
$query1 =mysqli_query($con,"SELECT semester FROM student WHERE username='$user'");
while($row1=mysqli_fetch_array($query1))
{
$sems=$row1['semester'];
}
$res=mysqli_query($con,"SELECT status FROM submitted_assignments WHERE s_name='$user'");
while($row2=mysqli_fetch_array($res))
{
$stat=$row2['status'];
}
?>
<table class="student" id= "student">
<form action="" method="post">
<thead>
<tr class="table100-head">
<th class="column0">Sl. No.</th>
<th class="column2">Assignment Name</th>
<th class="column2">Subject</th>
<th class="column1">Date</th>
<th class="column0">View</th>
<th class="column0">Status</th>
</tr>
</thead>
<tbody>
<?php
$shcat=mysqli_query($con,"SELECT * FROM assignment INNER JOIN subject ON assignment.as_subject=subject.s_id WHERE s_course='$cr' AND a_semester='$sems'");
$cnt=1;
while($row=mysqli_fetch_array($shcat)){
$stat = 0;
$res=mysqli_query($con,"SELECT status FROM submitted_assignments WHERE s_name='$user' AND a_name=".$row['a_id']);
while($row2=mysqli_fetch_array($res))
{
$stat=$row2['status'];
}
?>
<tr>
<td class="column0"><?php echo $cnt; ?></td>
<td class="column1"><?php echo $row['a_name'];?></td>
<td class="column2"><?php echo $row['s_name'];?></td>
<td class="column2"><?php echo $row['date'];?></td>
<td class="column0"><a target = "_blank" href="../faculty/assignment/<?php echo $row['image']?>"><i class="fa fa-eye"></i></a></td>
<?php
if ($stat == 0){ ?>
<td class="column0"><i class="fa fa-times" title="Not Submitted"></i></td>
<?php }
else {?>
<td class="column0"><i class="fa fa-check" title="Submitted"></i></td>
<?php }?>
</tr>
<?php $cnt=$cnt+1;
} ?>
</tbody>
</form>
</table>
From what i have tried it changes all the rows to check icon even if only one row's assignment is submitted.
Any help is much appreciated. Thank you.
Edit Its working now.
Your code to set $stat
$res=mysqli_query($con,"SELECT status FROM submitted_assignments WHERE s_name='$user'");
while($row2=mysqli_fetch_array($res))
{
$stat=$row2['status'];
}
is just going to override the value of $stat leaving the last rows value in its place.
The simple way to fix this will be to move this sql into the PHP for loop and check for the specific assignment+user combination. Without your database scheme im not sure the files used but something like:
<?php
$shcat=mysqli_query($con,"SELECT * FROM assignment INNER JOIN subject ON assignment.as_subject=subject.s_id WHERE s_course='$cr' and a_semester='$sems'");
$cnt=1;
while($row=mysqli_fetch_array($shcat)){
$stat = 0;
$res=mysqli_query($con,"SELECT status FROM submitted_assignments WHERE s_name='$user' AND a_name=".$row['a_name']);
while($row2=mysqli_fetch_array($res))
{
$stat=$row2['status'];
}
?>
<tr>
<td class="column0"><?php echo $cnt; ?></td>
<td class="column1"><?php echo $row['a_name'];?></td>
<td class="column2"><?php echo $row['s_name'];?></td>
<td class="column2"><?php echo $row['date'];?></td>
<td class="column0"><a target = "_blank" href="../faculty/assignment/<?php echo $row['image']?>"><i class="fa fa-eye"></i></a></td>
<?php
if ($stat == 0){ ?>
<td class="column0"><i class="fa fa-times" title="Not Submitted"></i></td>
<?php }
else {?>
<td class="column0"><i class="fa fa-check" title="Submitted"></i></td>
<?php }?>
</tr>
<?php $cnt=$cnt+1;
} ?>

Auto sum total in search filter only - not the whole db

<table id="resultTable" data-responsive="table" style="text-align: left; width: 400px;" border="1" cellspacing="0" cellpadding="4">
<thead>
<tr>
<th> Total </th>
<th> Deposit </th>
</tr>
</thead>
<tbody>
<?php
$result = $db->prepare("SELECT * FROM student");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr class="record">
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['contact']; ?></td>
</tr>
<?php
}
?>
</tbody>
<thead>
<tr>
<th> Total </th>
<th>
<?php
$results = $db->prepare("SELECT sum(contact) FROM student");
$results->execute();
for($i=0; $rows = $results->fetch(); $i++){
echo $rows['sum(contact)'];
}
?>
</th>
</tr>
</thead>
</table>
This is my code. I want to search a certain word only, and that item will generate the sum total, because right now it displays the whole sum of the row in the table. I want the search to generate the sum total can you help me?
While it's unclear what you're asking, here are the two scenarios I can imagine you want:
A count of rows matching "a certain word only":
$results = $db->prepare("SELECT sum(contact) FROM student");
First of all, sum is a GROUP BY Aggregate function. It's unlikely this is what you want in any run-of-the-mill scenario.
Change your query to this:
$results = $db->prepare("SELECT count(*) FROM student WHERE word = :word");
$results->execute( array( ":word" => "certain" ) );
This will count how many rows are returned when you have certain in the word column.
A sum of columns
Change your query to something like this:
$results = $db->prepare("SELECT ( number1 + number2 ) as totalNumber, * FROM student");
This will select every row and add an additional column to the result set called totalNumber that holds the sum (+) of the columns number1 and number2.

Loop through database query

I would like to show the results of one database table by the use of a variable fetched from another database table like this:
mysql_select_db($database_Connection, $Connection);
$query_Recordset_bids = "SELECT * FROM bids WHERE bidder = '$userName'";
$Recordset_bids = mysql_query($query_Recordset_bids, $Connection) or die(mysql_error());
while ($row_Recordset_bids = mysql_fetch_array($Recordset_bids)) {
$totalRows_Recordset_bids = mysql_num_rows($Recordset_bids);
mysql_select_db($database_Connection, $Connection);
$query_Recordset_jobs = "SELECT * FROM jobs WHERE userID = '".$row_Recordset_bids['jobID']."'";
$Recordset_jobs = mysql_query($query_Recordset_jobs, $Connection) or die(mysql_error());
$row_Recordset_jobs = mysql_fetch_assoc($Recordset_jobs);
$totalRows_Recordset_jobs = mysql_num_rows($Recordset_jobs);
}
And then I want the output showed in the following table:
<?php if($totalRows_Recordset_jobs == 0)
echo "You have never submitted a job offer!";
else {
?>
<table width="440" border="0" cellpadding="1" cellspacing="1" id="tablejobs">
<tr>
<th width="40" bgcolor="#779BDC" scope="col">ID</th>
<th width="90" bgcolor="#779BDC" scope="col">Destination</th>
<th width="85" bgcolor="#779BDC" scope="col">Cargo</th>
<th width="85" bgcolor="#779BDC" scope="col">Due Date</th>
<th width="75" bgcolor="#779BDC" scope="col">Bid</th>
<th width="65" bgcolor="#779BDC" scope="col">Status</th>
</tr>
<?php do { ?>
<tr>
<td height="22" bgcolor="#798890" scope="col"> <?php echo $row_Recordset_jobs['userID']; ?></td>
<td bgcolor="#798890" scope="col"> <?php echo $row_Recordset_jobs['destination']; ?></td>
<td bgcolor="#798890" scope="col"> <?php echo $row_Recordset_jobs['cargo']; ?></td>
<td bgcolor="#798890" scope="col"> <?php echo $row_Recordset_jobs['due_date']; ?></td>
<td bgcolor="#798890" scope="col"> <?php echo $row_Recordset_jobs['bids']; ?> kr.</td>
<td bgcolor="#798890" scope="col"> <?php echo $row_Recordset_jobs['status']; ?></td>
</tr>
<?php } while ($row_Recordset_jobs = mysql_fetch_assoc($Recordset_jobs)); ?>
</table>
<?php
}
?>
But there is only one row shown in the table even though there are 2 or more results that match the select query.
So how do I loop through the first database table to get multiple matching variables (jobID) that I can use to my select statement to the second database table, which should show multiple results?
I suggest you to simply learn about joins. :)
You can also use a join on different databases aslong as both databases are available with the same connection/credentials.
I am not sure if I got you right that you have two databases for your tables.
If you have only one database its simple:
$query = 'SELECT *
FROM bids b
LEFT JOIN jobs j ON b.jobID = j.UserID
WHERE b.bidder = "$userName"';
Incase you have two databases use this and insert names of your two databases for <namedb1> and <namedb2>.
However, note that this is not the smartest thing to do because you cannot use any indizes, transactions, constraints or table-locks over different databases.
(As mentioned by Jay Blanchard in the comments)
$query = 'SELECT *
FROM <namedb1>.bids b
LEFT JOIN <namedb2>.jobs j ON b.jobID = j.UserID
WHERE b.bidder = "$userName"';
http://dev.mysql.com/doc/refman/5.1/en/join.html

php splitting records in multiple pages is not working properly

i'm facing problem in getting the apprpriate values for some cells ....In the first page i'm getting the appropriate result..but in the next pages the values for product information,total price and profit from order all have value 0 but all the other fields are containing correct information.
Five records are shown per page.. The code is given below:
<?include"dbconnect.php"?>
session_start();
?>
<?include "adminhead.php"?>
<?include "adminleftnav.php"?>
<div id="seasonal">
<table width="635" border="0" align="left" bgcolor="#CCCCCC" >
<tr>
<td>
<table width="635" border="0" align="left" >
<tr>
<td width="52" bgcolor="#E0EBED">Order Number</td>
<td width="150" bgcolor="#E0EBED">Product Information</td>
<td width="100" bgcolor="#E0EBED">Total Price(TK)</td>
<td width="90" bgcolor="#E0EBED">Order Date</td>
<td width="80" bgcolor="#E0EBED">Payment Status</td>
<td width="100" bgcolor="#E0EBED">Profit from order(TK)</td>
</tr>
</table>
</td>
</tr>
<?php
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1)*5 ;
$sql = "Select distinct order_no,date,payment_status from product_order_info order by order_no ASC LIMIT $start_from,5";
$query_for_order1 = mysql_query ($sql);
?>
<tr>
<td>
<table id="foo" border="1" bgcolor="#f4eddb" cellspacing="2" cellborder="2" width=635>
<? while($row_for_my_order1=mysql_fetch_assoc($query_for_order1))
{
?>
<tr>
<td width=52>
<?echo $row_for_my_order1['order_no'];?>
</td>
<td width=156>
<?
$sql1 = "Select * from product_order_info where order_no= '$row_for_my_order1[order_no]' order by order_no ASC LIMIT $start_from,5";
$query_for_order = mysql_query($sql1);
while($row_for_my_order=mysql_fetch_assoc($query_for_order))
{
$query_for_product_details=mysql_query("select * from product where product_no='$row_for_my_order[product_id]' ");
$row_for_product_details=mysql_fetch_array($query_for_product_details);
?>
<br>
<?echo $row_for_product_details['product_name'];
?>
<br>
Quantity
<?echo $row_for_my_order['quantity'];
}
?>
</td>
<td width=106>
<?
$total=0;
$sql1 = "Select * from product_order_info where order_no= '$row_for_my_order1[order_no]' order by order_no ASC LIMIT $start_from,5";
$query_for_order = mysql_query($sql1);
while($row_for_my_order2=mysql_fetch_assoc($query_for_order))
{
$query_for_product_details=mysql_query("select * from product where product_no='$row_for_my_order2[product_id]' ");
$row_for_product_details=mysql_fetch_array($query_for_product_details);
$total = $total+ $row_for_product_details['sell_price'] * $row_for_my_order2['quantity'];
}
echo $total;
?>
</td>
<td width=90>
<?echo $row_for_my_order1['date'];?>
</td>
<td>
<?echo $row_for_my_order1['payment_status'];?>
</td>
<td width=100>
<? $total=0;
$sql1 = "Select * from product_order_info where order_no= '$row_for_my_order1[order_no]' order by order_no ASC LIMIT $start_from,5";
$query_for_order = mysql_query($sql1);
while($row_for_my_order3=mysql_fetch_assoc($query_for_order))
{
$total=$total+$row_for_my_order3['profit'];
}
echo $total; ?>
</td>
</tr>
<?
}
?>
</table>
</div>
<?php
$sql = "SELECT DISTINCT COUNT(order_no) FROM product_order_info";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 5);
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='view_order.php?page=".$i."'>".$i."</a> ";
};
?>
<?include "footer1.php"?>
Please help me in this regard...
You should delete LIMIT $start_from,5 from every query except the first one. As Dagon pointed out, you should consider the possibility to use a single query, to reduce the number of queries to the SQL server.

Categories