SELECT *, SUM(NET) AS TOTAL FROM TABLE1 WHERE CLAUSE - php

<?php require_once('../includes/connection.php');?>
<?php require_once('../includes/header.php');?>
<?php
$color="1";
$respo = $_GET['respo'];
$data = explode("+", $respo);
$month = date("m", strtotime($data[1])) . "<br />";
$year = date("Y", strtotime($data[1])) . "<br />";
**$viewrecord = "SELECT *, (pr.roll1 + pr.roll2 + pr.roll3 + pr.roll4 + pr.roll5 + pr.roll6) AS rolls FROM tbl_payroll dv join tbl_payroll pr on pr.dv_id = dv.dv_id WHERE dv.respo='".mysql_real_escape_string($data[0])."' && year(dv.date_added)='$year' && month(dv.date_added)='$month'";**
$run_viewrecord = mysql_query($viewrecord) or die(mysql_error());
{
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>
------------HEADER--------- etc....
-------THERE SHOULD BE A IF STATEMATE HERE-----------------
(where if no records match "dv.dv_id=pr.pr.dv_id". It would still display records from tbl_dv..)
while ($row = mysql_fetch_row($run_viewrecord)) {
if($color==1){
echo "<tr bgcolor='#ffffff'>";
echo "<td align='center'>" .date_format(date_create($row[17]), "m/d/y")."</td>
**--------- I WANT TO DISPLAY THE ROLLS HERE --------------------**
echo "</td></tr>";
$color="2";
} else {
echo "<tr bgcolor='#ebeaea'>";
echo "<td align='center'>" .date_format(date_create($row[17]), "m/d/y")."</td>
**--------- I WANT TO DISPLAY THE ROLLS HERE --------------------**
echo "</td></tr>";
$color="1";
}
}
echo '</table>';
echo '<td><tr><table><br /><br />';
}
?>
I was hoping to add an IF statement before WHILE. Which will still display records even there is no match dv_id on both table2. It should still display records.. The COLUMN ROLLS IF No match it will display a 0.00 value. LINK>> http://i599.photobucket.com/albums/tt79/emcevo/viewphpdisplay_zpsfc6a8174.jpg
//Total NET
<?php
$qry2 = "SELECT *, SUM(net) as sum_net FROM tbl_dv";
$run2 = mysql_query($qry2) or die(mysql_error());
while ($row = mysql_fetch_array($run2)) {
?>
<tr>
<td colspan="5" style="text-align:right;" /><b>TOTAL NET</b></td>
<td colspan="6" style="text-align:left;font-size: 14px;" /><b><?php echo number_format($row['sum_net'],2); ?></b></td>
</tr><?php }?>
</td></tr></table>
How can I display the TOTAL NET below code:
$qry2 = "SELECT *, SUM(net) as sum_net FROM tbl_dv";.
I top codes are all working.. The bold Section BUTTOM code is the Problem.

I guess you get downvotes because your whole php code-block is unnecessary as far I can see. Your query "$qry2" is incorrect; you can't sum without a group by (unless you only do a sum). eg:
select dv_id, sum(net) as sum_net from tbl_dv group by dv_id

Related

MySql/PHP Simple Report Query

I'm running a MySQL/PHP and i'm trying to display a simple report that tracks when a salesrep contacts a customer. I can't figure out what I'm doing wrong, as i'm a novice in this area. The simplest solution to me seems extremely convoluted (making a separate recordset for each figure). I figured there would have to be a simpler way.
I'm looking to display the number of contacts made during the current week/month/year in a simple table. see below. any help would be greatly appreciated.
|Current|Current| |
| Week | Month | YTD |
------|-------|-------|-------|
Brian | 7 | 14 | 37 |
------|-------|-------|-------|
Chad | 0 | 15 | 27 |
------|-------|-------|-------|
David | 11 | 26 | 52 |
------|-------|-------|-------|
Current recordsets
mysql_select_db($database_Sales, $Sales);
$query_rsCurWeek = "SELECT Sales.rep, COUNT(*) FROM Sales WHERE YEARWEEK(`date`, 1) = YEARWEEK(CURDATE(), 1) GROUP BY Sales.rep";
$rsCurWeek = mysql_query($query_rsCurWeek, $Sales) or die(mysql_error());
$row_rsCurWeek = mysql_fetch_assoc($rsCurWeek);
$totalRows_rsCurWeek = mysql_num_rows($rsCurWeek);
mysql_select_db($database_Sales, $Sales);
$query_rsCurMonth = "SELECT Sales.rep, COUNT(*) FROM Sales WHERE MONTH(date) = MONTH(CURDATE()) GROUP BY Sales.rep";
$rsCurMonth = mysql_query($query_rsCurMonth, $Sales) or die(mysql_error());
$row_rsCurMonth = mysql_fetch_assoc($rsCurMonth);
$totalRows_rsCurMonth = mysql_num_rows($rsCurMonth);
mysql_select_db($database_Sales, $Sales);
$query_rsCurYear = "SELECT Sales.rep, COUNT(*) FROM Sales WHERE YEAR(date) =
YEAR(CURDATE()) GROUP BY Sales.rep";
$rsCurYear = mysql_query($query_rsCurYear, $Sales) or die(mysql_error());
$row_rsCurYear = mysql_fetch_assoc($rsCurYear);
$totalRows_rsCurYear = mysql_num_rows($rsCurYear);
Current Output Table
<table width="400" border="1" cellspacing="0" cellpadding="0">
<tr>
<th width="175" align="center"></th>
<th width="75" align="center">Current<br />Week</th>
<th width="75" align="center">Current<br />Month</th>
<th width="75" align="center">YTD</th>
</tr>
<?php do { ?>
<tr>
<th align="left"><?php echo $row_rsCurYear['rep']; ?></th>
<td align="center"><?php echo $row_rsCurWeek['COUNT(*)']; ?></td>
<td align="center"><?php echo $row_rsCurMonth['COUNT(*)']; ?></td>
<td align="center"><?php echo $row_rsCurYear['COUNT(*)']; ?></td>
</tr>
<?php } while ($row_rsCurWeek = mysql_fetch_assoc($rsCurWeek)); ?>
try{
$sql = "SELECT * FROM contacts";
$result = $pdo->query($sql);
if($result->rowCount() > 0){
echo "<table>";
echo "<tr>";
echo "<th>username</th>";
echo "<th>current_week</th>";
echo "<th>current_month</th>";
echo "<th>ytd</th>";
echo "</tr>";
while($row = $result->fetch()){
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['current_week'] . "</td>";
echo "<td>" . $row['current_month'] . "</td>";
echo "<td>" . $row['ytd'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
unset($result);
} else{
echo "No records matching your query were found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}

how to show one of the image with same id from database in php?

<?php
$sqlget = "SELECT * FROM news_events,news_events_images WHERE news_events.id = news_events_images.newsId";
$sqldata = mysql_query($sqlget) or die('error getting data');
echo " <table class=\"table table-striped table-hover\" style=\"width:100%;\"> <thead><th colspan=\"2\"> <h3 style= \"font-family:Georgia;font-size:22px;text-transform:capitalize; text-align:center; color:#ec1e2e; \">News and events</h3> </th>";
echo"</thead><tbody>";
while ($row = mysql_fetch_array($sqldata, MYSQLI_ASSOC)) {
echo "<tr><td colspan=\"2\" style=\"width:100%;text-align:center;font-size:16px;font-weight:bold;padding:3em 0em;\">";
echo $row['Title'];
echo "</td></tr><tr><td style=\"width:30%;\">";
echo "<img src=\"Admin/images/newsImages/";
echo $row['image'];
echo "\"";
echo" class=\"image-responsive\" style=\"display:block; width:100%; height:auto;\">";
echo "</td><td style=\"width:70%;text-align:justify;\">";
echo $row['description'];
echo "</td>
</tr>";
}
echo "</tbody></table>";
?>
This code is displaying all the images row by row, but i want only one image should be displayed, In database i have 4 images under same id, from that i want to display one of the image
if you want to show only 1 image using same id then you group by
$sqlget = "SELECT * FROM news_events,news_events_images WHERE news_events.id = news_events_images.newsId group by news_events.id";
for more information group by
https://www.w3schools.com/sql/sql_groupby.asp

What is the error in the code and the SQL query? Why is nothing is displayed on the web page?

I am creating a web page that display for the user at first 4 dropdown lists that includes a retrieved data from MYSQL database. where each dropdown list represent 1 column in different tables.
I am using wordpress and $wpdb class
What I need is to be able to display the result to the user based on the user selections.
Example:
site id - site name - owner name - owner contact - lat - long - company name....
and all related columns.
The problem is that the system is just displaying the data selected in the dropdown list ... it looks like the system just return the data from the dropdown list and not from the database.
How can I fix this?
I will display part of the code and an image of the web page.
Code:
<?php
/*
Template Name: search info
*/
get_header();
?>
<?php
// code for submit button ation
global $wpdb;
//variables that handle the retrieved data from mysql database based on the ID of the variable in HTML (select)
if(isset($_POST['query_submit']))
{
if(isset($_POST['site_name']))
{
$site_name=$_POST['site_name'];
}
else { $site_name=""; }
if(isset($_POST['owner_name']))
{
$owner_name=$_POST['owner_name'];
}
else { $owner_name=""; }
if(isset($_POST['Company_name']))
{
$company_name=$_POST['Company_name'];
}
else { $company_name=""; }
if(isset($_POST['Subcontractor_name']))
{
$Subcontractor_name=$_POST['Subcontractor_name'];
}
else { $Subcontractor_name="";}
//query to retrieve all related info of the selected data from the dropdown list
$query_submit =$wpdb->get_results ("select
site_info.siteID,site_info.siteNAME ,site_info.equipmentTYPE,site_coordinates.latitude,site_coordinates.longitude,site_coordinates.height ,owner_info.ownerNAME,owner_info.ownerCONTACT,company_info.companyNAME,subcontractor_info.subcontractorCOMPANY,subcontractor_info.subcontractorNAME,subcontractor_info.subcontractorCONTACT from `site_info`
LEFT JOIN `owner_info`
on site_info.ownerID = owner_info.ownerID
LEFT JOIN `company_info`
on site_info.companyID = company_info.companyID
LEFT JOIN `subcontractor_info`
on site_info.subcontractorID = subcontractor_info.subcontractorID
LEFT JOIN `site_coordinates`
on site_info.siteID=site_coordinates.siteID
where
site_info.siteNAME = `$site_name`
AND
owner_info.ownerNAME = `$owner_name`
AND
company_info.companyNAME = `$company_name`
AND
subcontractor_info.subcontractorNAME = `$Subcontractor_name`
" , ARRAY_A);
$site_id = 'siteID';
$site_id = (array)$site_id;
$equipment_type = 'equipmentTYPE';
$equipment_type = (array)$equipment_type;
$lat='latitude';
$lat = (array)$lat;
$long='longitude';
$long = (array)$long;
$height = 'height';
$height = (array)$height;
$owner_contact = 'ownerCONTACT';
$owner_contact = (array)$owner_contact;
$sub_contact = 'subcontractorCONTACT';
$sub_contact = (array)$sub_contact;
$sub_company = 'subcontractorCOMPANY';
$sub_company = (array)$sub_company;
?>
<table width="30%" >
<tr>
<td>Site Name</td>
<td>Owner Name</td>
<td>Company Name</td>
<td>Subcontractor Name</td>
<td>Site ID</td>
<td>Equipment Type</td>
<td> Lattitude</td>
<td>Longitude </td>
<td> Height</td>
<td> Owner Contact</td>
<td> Sub Contact</td>
<td> Sub company Name</td>
</tr>
<tr>
<?php
foreach ($query_submit as $query)
{
echo "<table>";
echo "<tr>";
echo "<td>" ,$query[siteNAME]. "</td>";
echo "<td>", $query[ownerNAME] ."</td>";
echo "<td>", $query[companyNAME] ."</td>";
echo "<td>", $query[subcontractorNAME]. "</td>";
echo "<td>" ,$query[siteID ]."</td>";
echo "<td>" ,$query[equipmentTYPE]. "</td>";
echo "<td>" ,$query[latitude]. "</td>";
echo "<td>" ,$query[longitude]. "</td>";
echo "<td>" ,$query[height]. "</td>";
echo "<td>" ,$query[ownerCONTACT]. "</td>";
echo "<td>" ,$query[subcontractorCONTACT ]."</td>";
echo "<td>" ,$query[subcontractorCOMPANY]. "</td>";
echo "</tr>";
echo"</table>";
}
?>
</tr>
</table>
<?php
}
?>
After clicking of the submit button nothing is display ... where is the error?
i fixed the problem the error was in the displaying using echo ..i should use this format echo"".$obj->siteNAME."";.
thank you for your answers and comments

call or create session variable in SUM

I am not very familiar with PHP or MySQL, but after researching here I have been able to learn and get very close to what I need and build my first sum query. I am trying to read the database and sum values based on several variables.
I need the reservation_pax from the reservations table where reservation_time is 8:00 where reservation_hidden = 0 and reservation_date is something. I can manually enter the date and it works. I am now trying to use a session code already in the script or find a way to to dynamically add based on selected date.
Here is the code I have working without the dynamic aspect or session.
$result = mysql_query("SELECT SUM(reservation_pax)
FROM reservations
WHERE reservation_time = '8:00:00'
AND reservation_date = '2014-10-27'
AND reservation_hidden ='0'") ;
if ($result === false) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result)) {
echo $row['SUM(reservation_pax)'];
}
Here is the full code of the page where I entered the above addition. Can anyone help me figure out how to call the selected date rather than having to manually enter.
<!-- Begin reservation table data -->
<br/>
<table class="global resv-table-small" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<?php
echo "<td class='noprint'> </td>";
echo "<td>Time</td>";
echo "<td>Guests/Type</td>";
echo "<td>Name</td>";
echo "<td>Special Instructions/Notes</td>";
echo "<td class='noprint'>Table</td>";
echo "<td class='noprint'>Status</td>";
echo "<td class='noprint'>Created</td>";
echo "<td class='noprint'>Details/Delete</td>";
echo "</tr>";
// Clear reservation variable
$reservations ='';
if ($_SESSION['page'] == 1) {
$reservations = querySQL('all_reservations');
}else{
$reservations = querySQL('reservations');
}
// reset total counters
$tablesum = 0;
$guestsum = 0;
if ($reservations) {
//start printing out reservation grid
foreach($reservations as $row) {
// reservation ID
$id = $row->reservation_id;
$_SESSION['reservation_guest_name'] = $row->reservation_guest_name;
// check if reservation is tautologous
$tautologous = querySQL('tautologous');
echo "<tr id='res-".$id."'>";
echo "<td";
// daylight coloring
if ($row->reservation_time > $daylight_evening){
echo " class='evening noprint'";
}else if ($row->reservation_time > $daylight_noon){
echo " class='afternoon noprint'";
}else if ($row->reservation_time < $daylight_noon){
echo " class='morning noprint'";
}
echo " style='width:10px !important; padding:0px;'> </td>";
echo "<td id='tb_time'";
// reservation after maitre message
if ($row->reservation_timestamp > $maitre['maitre_timestamp'] && $maitre['maitre_comment_day']!='') {
echo " class='tautologous' title='"._sentence_13."' ";
}
echo ">";
echo "<strong>".formatTime($row->reservation_time,$general['timeformat'])."</strong></td>";
echo "<td id='tb_pax'><strong class='big'>".$row->reservation_pax."</strong> <span class='noprint'>";
printType($row->reservation_hotelguest_yn);
//echo "<img src='images/icons/user-silhouette.png' class='middle'/>";
echo "</span></td><td style='width:10%' id='tb_name'><span class='noprint'>".printTitle($row->reservation_title)."</span><strong> <a id='detlbuttontrigger' href='ajax/guest_detail.php?id=".$id."'";
// color guest name if tautologous
if($tautologous>1){echo" class='tautologous tipsy' title='"._tautologous_booking."'";}
echo ">".$row->reservation_guest_name."</a></strong>";
// old reservations symbol
if( (strtotime($row->reservation_timestamp) + $general['old_days']*86400) <= time() ){
echo "<img src='images/icons/clock-bolt.png' class='help tipsyold middle smicon' title='"._sentence_11."' />";
}
// recurring symbol
if ($row->repeat_id !=0) {
echo " <img src='images/icons/loop-alt.png' alt='"._recurring.
"' title='"._recurring."' class='tipsy' border='0' >";
}
echo"</td><td style='width:10%' id='tb_note'>";
if ($_SESSION['page'] == 1) {
echo $row->outlet_name;
}else{
echo $row->reservation_notes;
}
echo "</td>";
if($_SESSION['wait'] == 0){
echo "<td class='big tb_nr' style='width:85px;' id='tb_table'><img src='images/icons/table_II.png' class='tipsy leftside noprint' title='"._table."' /><div id='reservation_table-".$id."' class='inlineedit'>".$row->reservation_table."</div></td>";
}
echo "<td class='noprint'><div>";
getStatusList($id, $row->reservation_status);
echo "</div></td>";
echo "<td class='noprint'>";
echo "<small>".$row->reservation_booker_name." | ".humanize($row->reservation_timestamp)."</small>";
echo "</td>";
echo "<td class='noprint'>";
// MOVE BUTTON
// echo "<a href=''><img src='images/icons/arrow.png' alt='move' class='help' title='"._move_reservation_to."'/></a>";
// WAITLIST ALLOW BUTTON
if($_SESSION['wait'] == 1){
$leftspace = leftSpace(substr($row->reservation_time,0,5), $availability);
if($leftspace >= $row->reservation_pax && $_SESSION['outlet_max_tables']-$tbl_availability[substr($row->reservation_time,0,5)] >= 1){
echo" <a href='#' name='".$id."' class='alwbtn'><img src='images/icons/check-alt.png' name='".$id."' alt='"._allow."' class='help' title='"._allow."'/></a> ";
}
}
// EDIT/DETAIL BUTTON
echo "<a href='?p=102&resID=".$id."'><img src='images/icons/pen-fill.png' alt='"._detail."' class='help' title='"._detail."'/></a> ";
// DELETE BUTTON
if ( current_user_can( 'Reservation-Delete' ) && $q!=3 ){
echo"<a href='#modalsecurity' name='".$row->repeat_id."' id='".$id."' class='delbtn'>
<img src='images/icons/delete.png' alt='"._cancelled."' class='help' title='"._delete."'/></a>";
}
echo"</td></tr>";
$tablesum ++;
$guestsum += $row->reservation_pax;
}
}
?>
</tbody>
<tfoot>
<tr style="border:1px #000;">
<td class=" noprint"></td><td></td>
<td colspan="2" class="bold"><?php echo $guestsum;?> <?php echo _guest_summary;?></td>
<td></td>
<td colspan="2" class="bold"><?php echo $tablesum;?> <?php echo _tables_summary;?></td>
<td colspan="2" class="bold"><?php
$result = mysql_query("SELECT SUM(`reservation_pax`) FROM `reservations` WHERE `reservation_time` = '8:00:00' AND `reservation_date` = '{$_SESSION['selectedDate']}' AND `reservation_hidden` ='0'") ;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['SUM(reservation_pax)'];
}
?>
<?php echo '/ 40 ', _guest_summary, ' -8:00 AM';?></td>
<td></td>
<?php
if($_SESSION['wait'] == 0){
//echo "<td></td>";
}
?>
</tr>
</tfoot>
</table>
<!-- End reservation table data -->
you can use alias field, as:
$result = mysql_query("SELECT SUM(reservation_pax) AS reserve_sum
FROM reservations WHERE reservation_time = '8:00:00'
AND reservation_date = '2014-10-27'
AND reservation_hidden ='0'"
) ;
....
and get access it as:
while($row = mysql_fetch_array($result))
{
echo $row['reserve_sum'];
}
$result = mysql_query("SELECT SUM(reservation_pax) FROM reservations WHERE reservation_time = '8:00:00' AND reservation_date = '{$_SESSION['selectedDate']}' AND reservation_hidden ='0'") ;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['SUM(reservation_pax)'];
}
?>

PHP is there a simpler and tidier way of doing this?

I am trying to create a menu where users can view a menu that they create. The menu consists of a dropdown box which the users use to filter the menu by week.
The menu then displays the seven days of the week and the five types of meal times their are which is breakfast, lunch, dinner, pudding and snack. Below is how i am currentley displaying it so far.
$sqlmeasurement = mysql_query("SELECT title FROM recipe JOIN menu ON recipe.recipeid = menu.recipeid WHERE menu.weekid = '".$selectweek."' AND menu.mealtimeid = '1'") or die(mysql_error());
Print '<table border="0">
<tr>
<th width="100"> </th>
<th width="200">Monday</th>
</tr>';
echo "<tr>";
echo "<td><strong>Breakfast</strong></td>";
echo "<td>";
while($info = mysql_fetch_array( $sqlmeasurement ))
{
echo $info['title'];
echo "<br/>";
}
echo "</td> ";
echo "</tr>";
echo "</table>";
As you can see this PHP statement selects what i want from the table but because there are 7 days a week and 5 types of meal times this means that i will have to copy this code 35 times in order to display all that i want.
So for example the next bit of code will be like this:
$sqlmeasurement2 = mysql_query("SELECT title FROM recipe JOIN menu ON recipe.recipeid = menu.recipeid WHERE menu.weekid = '".$selectweek."' AND menu.mealtimeid = '2'") or die(mysql_error());
Print '<table border="0">';
Print '<tr>
<th width="100"> </th>
<th width="200"> </th>
</tr>';
echo "<tr>";
echo "<td><strong>Lunch</strong></td>";
echo "<td>";
while($info2 = mysql_fetch_array( $sqlmeasurement2 ))
{
echo $info2['title'];
echo "<br/>";
}
echo "</td> ";
echo "</tr>";
echo "</table>";
And so on until i have all the days and their meal times.
Is there a way to display all the information without all this iteration?
You have various options. You could put the output into a function, and just call that with varying parameters.
function ouptutMeal($selectweek, $mealtime, $mealname) {
$sqlmeasurement2 = mysql_query("SELECT ... WHERE menu.weekid = '$selectweek' AND menu.mealtimeid = '$mealtime'");
echo "<table>
<tr>
<th> </th>
<th> </th>
</tr>
<tr>
<td><strong>$mealname</strong></td>
<td>";
while($info2 = mysql_fetch_array( $sqlmeasurement2 )) {
echo $info2['title'], '<br/>';
}
echo '</td>
</tr>
</table>';
}
ouptutMeal($selectweek, 1, 'breakfast');
ouptutMeal($selectweek, 2, 'lunch');
Or you could use a different query to get all the information at once, and loop through it:
$q = "SELECT title, mealtimeid, mealtimename
FROM ...
WHERE menu.weekid = '$selectweek'
ORDER BY menu.mealtimeid";
You can then iterate through the results, assembling them into, say, a 2D array based on using mealtimename as a key. e.g.
$mealInfo = array()
while($info = mysql_fetch_array( $result )) {
$mealInfo[$info['mealtimename'][] = $info;
}
foreach ($mealInfo as $mealName => $mealData) {
ouptutMeal($mealName, $mealData);
}

Categories