I am new to PHP, and was wondering if you could help with my select sum query?
I am wanting to add the total amount from my expenses table in my database based on user_id?
Here is what I have so far
<?php
//sets up thisPage
$pageSize=10;
if (isset($_POST["thisPage"]))
$thisPage = $_POST["thisPage"];
else
$thisPage=1;
//selects all distinct expenses that have been uploaded
$dbQuery="SELECT SUM(amount) AS TotalExpenditure FROM expenses WHERE user_id = '$userID'; ";
echo $dbQuery;
$dbResult=mysqli_query($db_connection, $dbQuery) or die (mysqli_error($db_connection));
echo "<table> <thead>";
//echo '<tr> <th>Project ID</th><th>Project Name</th></tr> </thead>';
while ($dbRow=mysqli_fetch_array($dbResult)){
// display row with expense
echo '<tr> <td>'. $dbRow['amount'] .'</td>';
}
echo "</table>";
echo "</form>";
?>
You have
$dbRow['amount']
but you use
SUM(amount) AS TotalExpenditure
// ^ this is the name (alias) of your column now
TotalExpenditure is the name of the amount, so the last part should be
echo '<tr> <td>'. $dbRow['TotalExpenditure'] .'</td> </tr>';
You have to use TotalExpenditure as key of your array, so
$dbRow['TotalExpenditure'] instead of $dbRow['TotalExpenditure']?
You're giving an alias to your count() sql function so you have to use it
Related
I am trying to record the attendance of my students that attend my courses. Courses are different lengths and times and I just need to record if a student is (P)resent (L)ate (A)sent. I record the attendance in 1 table and display the records in a pivot table based on the date attended. I am a newby and just can't workout this code to include all the details I need to show. id, bid, fullname, nickname, company_idno, (P)(L)(A).
Please could someone look at my code and tell me how to add this information to the pivot table.
This is what I want to show
This is where I store the information
This is table1
This is table2
At the moment I achieved the look I want but use 2 tables and use CSS to fix the widths of table 1 and place table 2 next to it.
I realize this is terrible practice and of course, I get odd results across different platforms, especially iOS which put a 47px gap between the 2 tables which I can't seem to remove also.
I want just want table 2 to show all the information. I can only show 3 fields, id, date, pla. How to add fullname, nickname and company_idno ??
Table 1
<table id="tblplanames" >
<td id="tdplabc">sid</td>
<td id="tdplabc">bid</td>
<td id="tdplacid" style="text-align: center">Cid</td>
<td id="tdplafn" style="text-align: center">Fullname</td>
<td id="tdplann" style="text-align: center">Nickname</td>
<?php
$sql13="SELECT * FROM students WHERE classno='$id' ORDER BY bluecard_no ASC ";
$sql_row13=mysqli_query($link,$sql13);
while($sql_res13=mysqli_fetch_assoc($sql_row13)) {
$stsid=$sql_res13["id"];
$stidno=$sql_res13["company_idno"];
$stbluecard_no=$sql_res13["bluecard_no"];
$stfullname=$sql_res13["fullname"];
$stnickname=$sql_res13["nickname"];
?>
<tr>
<td id="tdplabc"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stsid; ?></td>
<td id="tdplabc"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stbluecard_no; ?></td>
<td id="tdplacid"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stidno; ?></td>
<td id="tdplafn"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stfullname; ?></td>
<td id="tdplann"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stnickname; ?></td>
</tr>
<?php
}
?>
</table>
Table 2
<?php
$id = $_GET['id'];
$sql = "SELECT DISTINCT date
FROM attendance
WHERE classno = $id
ORDER BY DATE";
$res = $link->query($sql); // mysqli query
while ($row = $res->fetch_row()) {
$dates[] = $row[0];
}
/***********************************
* Table headings *
************************************/
$emptyRow = array_fill_keys($dates,'');
// format dates
foreach ($dates as $k=>$v) {
$dates[$k] = date('d-M', strtotime($v));
}
$heads = "<table id='tblpla'>\n";
$heads .= "<tr><td>sid</td><td>" . join('</td><td>', $dates) . "</td></tr>\n";
/***********************************
* Main data *
************************************/
$sql = "SELECT date, sid, pla, bluecard_no
FROM attendance
WHERE classno = $id
ORDER BY bluecard_no";
$res = $link->query($sql);
$sid='';
$tdata = '';
while (list($d, $sn, $s, $bcn) = $res->fetch_row()) {
if ($sid != $sn) {
if ($sid) {
$tdata .= "<tr><td>$sid</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n";
}
$rowdata = $emptyRow;
$sid = $sn;
}
$rowdata[$d] = $s;
}
$tdata .= "<tr><td>$sid</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n";
$tdata .= "</table\n";
echo $heads;
echo $tdata;
?>
SELECT c.olumns
, y.ou
, a.ctually
, w.ant
FROM students s
JOIN attendance a
ON a.classno = s.classno
WHERE s.classno = :id
ORDER
BY s.bluecard_no ASC
, a.date";
public function get_members_for_attendence()
{
$date = $this->input->post('choose_date');
$sql = 'SELECT a.date, c.member_name,c.member_join_date,c.member_payment_date,c.member_exp_date,c.member_payment_date,c.member_contact, c.member_reg_id,
CASE
WHEN a.status = "absent" THEN "Absent"
WHEN a.status = "present" THEN "Present"
ELSE "Not Taken"
END as attendence_status
FROM member_reg AS c
LEFT JOIN attendence AS a ON a.member_reg_id = c.member_reg_id AND a.date = "'.$date.'"';
$query = $this->db->query($sql);
return $query->result();
}
For CodeIgniter 3
it worked for me
I have a database that has information on actors, roles, and movies.
On an HTML page I have the user input the first name and last name of an actor.
This form is then submitted to my PHP page where I look through my database, and provide the user with a 3 column html table with the following information: Movie Name the actor has worked in, Role the actor played, and year of movie.
All these information are in separate database tables. Examples of what each table looks like is below:
actor table contains:
'id', 'first_name', 'last_name', and 'gender' stored in the following way - (933,'Actor','Name','M')
role table contains:
'actor_id', 'movie_id', 'role stored in the following way - (16844,10920,'Role')
movies table contains:
'id', 'name', 'year', 'rank' stored in the following way - (306032,'Snatch.',2000,7.9)
I have to look through and correlate all the data into a table. This is what I have so far:
$sql ="SELECT id, first_name, last_name FROM actors";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
if ($row['first_name'] == $firstname && $row['last_name'] == $lastname) {
$actorID = $row['id'];
echo "$actorID<br>";
}
}//end while
$sql2 = "SELECT actor_id, movie_id, role FROM roles";
$result2 = mysql_query($sql2);
while ($row=mysql_fetch_array($result2)) {
if ($row['actor_id'] == $actorID) {
$movieID = $row['movie_id'];
$actRole = $row['role'];
echo "$movieID <br>";
echo "$actRole <br>";
}
} //end while
$sql3 = "SELECT id, name, year FROM movies";
$result3 = mysql_query($sql3);
while ($row=mysql_fetch_array($result3)) {
if ($row['id'] == $movieID) {
$movieName = $row['name'];
$movieYear = $row['year'];
echo "$movieName <br>";
echo "$movieYear <br>";
}
} //end while
echo '
<table>
<thead>
<tr>
<th> Movie Name </th>
<th> Actor Role </th>
<th> Release Date </th>
</tr>
</thead>
<tbody>
<td>'. $movieName .'</td>
<td>'. $actRole. '</td>
<td>'. $movieYear. '</td>
</tbody>
</table>';
?>
My solution works -- just a mediocre way of doing it
You don't have assign the variables $firstname and $lastname. Apart from that your if condition is wrong true every time.
if ($row['first_name'] = $firstname && $row['last_name'] = $lastname) {
Should be:
if ($row['first_name'] == $firstname && $row['last_name'] == $lastname) {
Also check what you want to do with the echo $row['first_name'][0];
Note that mysql_* functions are deprecated so you better use mysqli or PDO.
EDIT:
You can select all actors that have play in a movie using the following query. You can adjust to take only the information you need changing SELECT clause or using WHERE.
$sql = "
SELECT aa.id AS actor_id, aa.first_name, aa.last_name, cc.name, cc.year
FROM actor AS aa
INNER JOIN role AS bb
ON aa.id = bb.actor_id
INNER JOIN movies AS cc
ON cc.id = bb.movie_id";
EDIT 2: (from comments)
You can use the following code:
$conn = mysqli_connect("localhost", "db_username", "your_password", "your_database");
$query = "
SELECT aa.id AS actor_id, aa.first_name, aa.last_name, cc.name AS movie_name, cc.year AS release_year
FROM actor AS aa
INNER JOIN role AS bb
ON aa.id = bb.actor_id
INNER JOIN movies AS cc
ON cc.id = bb.movie_id";
$result = mysqli_query($conn, $query);
echo '
<table>
<thead>
<tr>
<th>Actor id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Movie name</th>
<th>Release date</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result)) {
echo '<td>'.$row['actor_id'].'</td>';
echo '<td>'.$row['first_name'].'</td>';
echo '<td>'.$row['last_name'].'</td>';
echo '<td>'.$row['movie_name'].'</td>';
echo '<td>'.$row['release_year'].'</td>';
}
echo '
</tbody>
</table>';
Hi in the below i want to show Consultation Charges values for that i took the td.But in that td not displying anything even td also not showing.
After executing this query i want to find the no. of rows based on the rows i want to display the data.
My expected output:
Bill Particular Bill Sub Particular Doctor Date Dis. Amt.
Consultation Charges:
all the values based on no of rows.
php
<table width="100%">
<th>Bill Particular</th>
<th>Bill Sub Particular</th>
<th>Doctor</th>
<th>Date</th>
<th>Dis. Amt.</th>
<th>Charge</th>
<th>No. of Times</th>
<th>Amount</th>
</table>
<tr><th colspan=2>Consultation Charges:</th>
<?php
$div_options = array();
$sql = "SELECT ibp.ipd_bp_id, ibp.bp_id, bp.bp_name, ibp.bsp_id, bsp.bsp_name, ibp.doctor_id, ab.employee_name doctor, ibp.date date, ibp.amount charge, ibp.discount_amount discount, ibp.no_of_time, (ibp.no_of_time * ibp.amount) total_amount
FROM bill_particular_master bp
INNER JOIN ipd_bill_particular ibp ON ibp.bp_id = bp.bp_id
LEFT OUTER JOIN bill_sub_particular bsp ON bsp.bsp_id = ibp.bsp_id
LEFT OUTER JOIN address_book ab ON ab.employee_id = ibp.doctor_id
WHERE ibp.ipd_reg_no = '$ipd_no'
AND bsp.consultant =1
AND bsp.package = 0
AND bsp.admission = 0
AND bp.bp_name != 'Scan Charges'
AND bp.bp_name !='Procedure'";
$sth = $dbh->query($sql);
//$row=$dbh->fetch();
$i=1;
while($row=$sth->fetch(PDO::FETCH_ASSOC)){
$sub_arr['bp_name'] = $row['bp_name'];
$sub_arr['bsp_name'] = $row['bsp_name'];
echo "<tr>
<td>Here is the text - " . $sub_arr['bp_name'] . "</td>
<td>The ID of the text is - " .$sub_arr['bsp_name'] . "</td>";
if($i !== 0) {
echo "<td>The ID of the previous entry is - " .$sub_arr['bp_name'] . "</td>";
}
else {
echo "<td> </td>";
}
echo "</tr>";
$i = $row['bp_name'];
}
?>
</tr>
echo "<td>The ID of the previous entry is - " . $row['bp_name'] . "</td>";
You have there variable thats not even defined in your code.
Sorry if I do something wrong it is my first time using stackflow and just beginning php and mysql.
The problem I am getting is that the table updates AFTER it echos. I would like to display the updated table.
while($row = mysql_fetch_array($result)) {
$bids = $row['bids'];
$bids +=1;
mysql_query("UPDATE items SET bids = " .$bids.", cost=" . $price. " WHERE items.name =". $item );
echo "<tr>
<td>".$row['name']."</td>
<td align=\"right\">".$row['cost']."</td>
<td align=\"right\">".$row['bids']."</td>
<td align=\"right\">".$row['seller_name']."</td>
</tr>";
}//end while
You need to add one more line in between your update statement and display statement.
$new_record = mysql_fetch_array(mysql_query("SELECT * FROM items WHERE items.name =". $item"));
Then use your echo statement as :
echo "<tr><td>".$new_record ['name']."</td>
<td align=\"right\">".$new_record['cost']."</td>
<td align=\"right\">".$new_record['bids']."</td>
<td align=\"right\">".$new_record['seller_name']."</td>
</tr>";
You should select rows from the table again, if You want to show them after update. In the code snippet above You actually echos old entries from the table.
Just wrap it in an if block
if(mysql_query("UPDATE items SET bids = " .$bids.", cost=" . $price. " WHERE items.name =". $item )){
echo "<td>".$new_record ['name']."</td>
<td align=\"right\">".$new_record['cost']."</td>
<td align=\"right\">".$new_record['bids']."</td>
<td align=\"right\">".$new_record['seller_name']."</td>
</tr>";
}
<?php require_once('../includes/header.php');?>
<?php require_once('../includes/connection.php');?>
<?php include('../includes/get_username.php');?>
<?php
include('sanitise.php');
$month = sanitise($_GET['month']);
?>
<table id="contentbox">
<tr>
<td>
<?php
$color="1";
//view record
$qry = mysql_query("SELECT * FROM tbl_dv WHERE monthname(date_added) = '$month' ORDER BY dv_id DESC");
echo "<table class='dvr_table' id='alternatecolor' width='100%'>
<tr>
<th>DATE ADDED</th>
<th>CT</th>
<th>PAYEE</th>
<th>PARTICULAR</th>
<th>PM</th>
<th>VOUCHER NO.</th>
<th>NET</th>
<th>OBR NO.</th>
<th>";
//RESPO/Office
$sql = "SELECT respo FROM tbl_dv WHERE monthname(date_added) = '$month' GROUP BY respo";
$result = mysql_query($sql);
echo "<select name='respo'>
<option value=' ' disabled='disabled' selected='selected'>Select a RESPO/Office</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['respo'] . "'>" . $row['respo'] . "</option>";
}
echo "</th>
<th>ACCOUNT CODE</th>
<th>FPP CODE</th>
<th>DEDUCTION</th>
</tr>";
while ($row = mysql_fetch_array($qry)) {
$dv_id = $row['dv_id'];
if($color==1){
echo "<tr bgcolor='#ffffff'>
<td style='text-align:center;'>" .date_format(date_create($row['date_added']), 'm/d/y')." </td>
<td style='text-align:center;'>" .$row['cashtype']."</td>
etc.......
$color="2";
} else {
echo "<tr bgcolor='#ebeaea'>
<td style='text-align:center;'>" .date_format(date_create($row['date_added']), 'm/d/y')." </td>
<td style='text-align:center;'>" .$row['cashtype']."</td>
etc......
$color="1";
}
}
echo "</tr>";
?>
I Have all it work. Only 1 PROBLEM.. I CANNOT DISPLAY the selected RESPO/OFFICE. As I select the RESPO/OFFICE it will sort out the selected RESPO/OFFICE... What should I resvise my code or add code.. Please Help!
A few suggestions first:
mysql is depreciated and you should move to PDO prepared statements
or mysqli. You can consult the php manual for this.
comment your code, you are not able to follow along unless you read
from top to bottom.
Now onto your code:
<?php
// Start document with includes needed, header, connection, functions.
require_once('../includes/header.php');
require_once('../includes/connection.php');
include('../includes/get_username.php');
include('sanitise.php');
// Start with the month variable posted from $_GET, this will begin the initial display.
$month = sanitise($_GET['month']);
?>
<!-- Begin Table Display and Layout -->
<table id="contentbox">
<tr>
<td>
<?php // Open PHP Tag to get variables to display in the table
$color="1";
// Initial Query to get the data for the month passed by GET, ordering by dv_id.
$qry = mysql_query("SELECT * FROM tbl_dv WHERE monthname(date_added) = '$month' ORDER BY dv_id DESC");
// Format the table rows for display
echo "<table class='dvr_table' id='alternatecolor' width='100%'>
<tr>
<th>DATE ADDED</th>
<th>CT</th>
<th>PAYEE</th>
<th>PARTICULAR</th>
<th>PM</th>
<th>VOUCHER NO.</th>
<th>NET</th>
<th>OBR NO.</th>
<th>";
// Fill the SELECT option with all the RESPO/Office data
$sql = "SELECT respo FROM tbl_dv WHERE monthname(date_added) = '$month' GROUP BY respo";
$result = mysql_query($sql);
// Display the select with the newly populated content
echo "<select name='respo'>
<option value=' ' disabled='disabled' selected='selected'>Select a RESPO/Office</option>";
// While the result contains data we will display respo as a select option.
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['respo'] . "'>" . $row['respo'] . "</option>";
}
// Finish the table header
echo "</th>
<th>ACCOUNT CODE</th>
<th>FPP CODE</th>
<th>DEDUCTION</th>
</tr>";
// While we have data from the original query we will display it
while ($row = mysql_fetch_array($qry)) {
$dv_id = $row['dv_id']; // grab the dv_id
if($color==1){ // Setup color scheme
echo "<tr bgcolor='#ffffff'> // Color for the row
// Let's begin filling the table with data
<td style='text-align:center;'>" .date_format(date_create($row['date_added']), 'm/d/y')." </td>
<td style='text-align:center;'>" .$row['cashtype']."</td>
etc.......
$color="2";
} else {
echo "<tr bgcolor='#ebeaea'>
<td style='text-align:center;'>" .date_format(date_create($row['date_added']), 'm/d/y')." </td>
<td style='text-align:center;'>" .$row['cashtype']."</td>
etc......
$color="1";
}
}
echo "</tr>";
?>
After reviewing the above code it is clear that you haven't setup a query to filter the data that you are displaying based on the selected option.
Your first query:
// Initial Query to get the data for the month passed by GET, ordering by dv_id.
$qry = mysql_query("SELECT * FROM tbl_dv WHERE monthname(date_added) = '$month' ORDER BY dv_id DESC");
You could append a new variable for the selected option, expand your WHERE statement. WHERE monthname(date_added) = '$month' && respo = '$respo' and move this query after the select option so it has access to the value chosen by the select option. Lastly, unless you are going to use jQuery to deal with the select box changing values, you would need a submit button to show the state change for the select option.
Pseudo Code:
Check for Submit
Change value of the department in the query WHERE clause
Display the requested data
This should get you in the direction you need to go in order to achieve the desired result.
EDIT:
In the 3rd answer you posted:
$viewrecord = "SELECT * FROM tbl_dv WHERE respo='".mysql_real_escape_string($respo)."' AND year(date_added)='$year' GROUP BY date_added ";
You said it is not filtering by the month being passed in, you are not adding it into your query, specifically the WHERE clause. So it should be:
$viewrecord = "SELECT * FROM tbl_dv WHERE respo='".mysql_real_escape_string($respo)."' AND month(month_added)='$month' AND year(date_added)='$year' GROUP BY date_added ";
FINAL EDIT:
Your first issue stems from not sending the $_GET['date_added'] value to the view page, so you will never display anything. Properly format the select box and add the data for the RESP and Date data from the database:
echo "<option value='". $row['respo'] . "+". $row['date_added'] . "'>" . $row['respo'] . " (".$row['count(*)'].")</option>";
Now that we are passing the respo and the date string we can work with the data on the next page:
/* UNCOMMENT NEXT LINE FOR ERROR DETECTION */
//error_reporting( E_ALL );
/* GET THE ENTIRE STRING PASSED FROM THE SELECT OPTION */
$respo = $_GET['respo'];
/* EXPLODE THE DATA BY + SYMBOL TO GET THE DATA */
$data = explode("+", $respo);
/* FORMAT THE DATETIME FROM THE STRING TO A FRIENDLY FORMAT */
$month = date("m", strtotime($data[1])) . "<br />";
$year = date("Y", strtotime($data[1])) . "<br />";
This is how I choose to work with the data and get what I needed, so now the query would be:
$viewrecord = "SELECT * FROM tbl_dv WHERE respo='".mysql_real_escape_string($data[0])."' && year(date_added)='$year' && month(date_added)='$month' ";
This will only display the records for the RESPO and the date by year and month passed into the page via $_GET.
<?php require_once('../includes/header.php');?>
<?php
$respo = $_GET['respo'];
$month = (int) (!empty($_GET['date_added']) ? $_GET['date_added'] : date('m'));
$year = (int) (!empty($_GET['date_added']) ? $_GET['date_added'] : date('Y'));
//database call here
$viewrecord = "SELECT * FROM tbl_dv WHERE respo='".mysql_real_escape_string($respo)."' AND year(date_added)='$year' GROUP BY date_added ";
$result = mysql_query($viewrecord, $db) or die (mysql_error());
$num_result = mysql_num_rows($result);
{
echo "<table border='1' width='100%' style='border:1px solid silver' cellpadding='5px' cellspacing='0px'>
<tr bgcolor='#666666' style='color:#FFFFFF'>
<th>Date Encoded</th>
etc...... (header here)
while ($row = mysql_fetch_row($result)) {
echo '<tr>';
echo "<tr ><td align='center'>" .date_format(date_create($row[17]), "m/d/y")."</td>
etc...
}
mysql_close($db);
?>
This is the code i come up. This is just an alternative solution. But the problem with this solution is that. I won't display the record in MONTH as call. THe respo is working as I select the RESPO it will display the all RESPO I ask, but the problem is that it include all the previous months with the RESPO I select. When I just select the specific month only..
//RESPO/Office
**echo '<form action="view.php" method="post">';**
$byrespo = mysql_query("SELECT DISTINCT count(*), respo FROM tbl_dv WHERE monthname(date_added)='$month' GROUP BY respo");
echo "<select name='respo' onchange='this.form.submit()'>
<option value=' ' disabled='disabled' selected='selected'>Select a RESPO/Office</option>";
while ($row = mysql_fetch_array($byrespo)) {
echo "<option value='" . $row['respo'] . "'>" . $row['respo'] . " (".$row['count(*)'].")</option>";
}
echo "</select></form>";
I just rushing to came up with solution.. So I add a and I create another view.php