PHP Row and Column Count - php

I was wondering if you guys can help me, I am pulling Data from a mysql database and I am looking to have the content echo in rows, like a shopping cart. Below is the code I am using. The Code is working flawlessly, but I don't know how to add the Row Count to it and Column Count to it.
Working Code:
<?
$dmealh = mysql_query("select count(*) from jobs_cart where mid='$mid'");
$jmealh = mysql_fetch_array($dmealh);
if ($jmealh[0]) {
$dmealh = mysql_query("select * from jobs_cart where mid='$mid' order by date desc, time desc");
while ($jmealh = mysql_fetch_array($dmealh)) {
echo "$id - $jmealh[name] - $jmealh[meals]";
}
}
?>
This is what I want the Data to look like:
Row Count- Name - Meal Count
1 - Greg - 3
2 - Mike - 4
3 - Tomm - 1
8 Meals Total

Just use a basic counter to keep track of what row you are on and use another variable to add up the meal count as you loop through your results and then echo out the final count. Throw it all into a table and you're set.
<?php
$dmealh = mysql_query("select count(*) from jobs_cart where mid='$mid'");
$jmealh = mysql_fetch_array($dmealh);
if ($jmealh[0]) {
$dmealh = mysql_query("select * from jobs_cart where mid='$mid' order by date desc, time desc");
$total_meals = 0; // Keep track of the total number of meals. Start at zero.
$row = 1; // Keep track of current row. Start at one.
?>
<table>
<?php
while ($jmealh = mysql_fetch_array($dmealh)) {
?>
<tr>
<td><?php echo $row; ?></td>
<td><?php echo $jmealh['name']; ?></td>
<td><?php echo $jmealh['meals']; ?></td>
</tr>
<?php
$total_meals += $jmealh[meals]; // Add to total meals
$row++; // Increase row count
}
?>
<tr>
<td></td>
<td></td>
<td><?php echo $total_meals; ?> Meals Total</td>
</tr>
</table>
}

Don't use mysql_* functions...they're deprecated (note the red box near the top).
Where does $mid come from? Make sure to escape your database inputs to prevent SQL injection.
You're doing extra work by first querying to see if any rows are returned. Just do the SELECT query and while loop. If no rows are returned, the loop will not execute.
You should be using an HTML table to display this data. Use PHP variables to keep track of your sums.
A crude example:
$mid = mysqli_real_escape_string($mid);
$rows = $total = 0;
$result = mysqli_query("SELECT name, meals FROM jobs_cart WHERE mid = '$mid' ORDER BY date DESC, time DESC");
echo '<table>';
while ($row = mysqli_fetch_assoc($result)) {
$rows++;
$total += $row['meals'];
echo '<tr><td>'. $rows .'</td><td>'. $row['name'] .'</td><td>'. $row['meals'] .'</td></tr>';
}
echo '<tr><td> </td><td> </td><td>'. $total .'</td></tr></table>';

Related

Fetching Specific Orders

This is the query I have written to fetch the records from 3 different tables and display them in one simple table.
$order_id=$_REQUEST['a'];
$query="select DISTINCT product.productId,orders.id,retailerName, total, status, delivery,shopName,ownerName,address,email,contact,notes,order_item.quantity,order_item.date,productName,price,product.detail,product.price,product.expiry from orders,checkout,order_item,product where product.productId=order_item.productId and orders.id ='".$order_id."' and orders.id=order_item.orderId and orders.id=checkout.orderId";
$res=mysqli_query($conn,$query);
$row=mysqli_fetch_array($res);
The below code is written for display of record and detail.
<?PHP
while($row=mysqli_fetch_array($res)){
?>
<tr>
<?php
$subtotal=0;
$subtotal = $row['quantity'] * $row['price'];
$total += $subtotal;
?>
<td><?php echo $row['productName'];?></td>
<td><?php echo $row['quantity'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $subtotal;?></td>
</tr>
<?PHP
}
?>
It displays all of the orders from database whereas I want the orders to be displayed for specific company.
If you have button for show only one result you should link it with some id.
For example:
Delete
Make SQL query show only one result: use WHERE clause.
if(isset($_GET['id'])) {
$id = $_GET['id'];
$q = "DELETE FROM table WHERE id = '$id'";
}
$db->query($q);

How to show few columns and then rest of other columns in php while loop?

I am showing all rows from mysql database using following php loop :
<tr>
<?php
$get_status = mysqli_query($link, "SELECT * FROM status ORDER BY status_order ASC");
while($status_result = mysqli_fetch_array($get_status) ) {
$status_name = htmlspecialchars($status_result['status_name']);
$status_order = htmlspecialchars($status_result['status_order']);
echo "<td><input type='checkbox' name='$status_name' value='$status_name'>$status_name</td>";
}
?>
</tr>
As a result, It's look like that :
But what I want is following :
I want to show only 5 columns and then 5 columns and then remaining one and so on...in php while loop. How can I do this ?
Add a variable to keep track of the number, then conditionally make a new row, like so:
<?php
$get_status = mysqli_query($link, "SELECT * FROM status ORDER BY status_order ASC");
$n = 0; //Keep track
while($status_result = mysqli_fetch_array($get_status) ) {
$status_name = htmlspecialchars($status_result['status_name']);
$status_order = htmlspecialchars($status_result['status_order']);
echo "<td><input type='checkbox' name='$status_name' value='$status_name'>$status_name</td>";
$n++; //Increase $n
if($n%5===0) echo "</tr><tr>"; //Make a new row every 5 iterations of loop
}

mysql Sum() and percentage from the total sum

I have a query running fine with results how ever I want to be able to calculate the sum of the votes and get the percentage. I guess I have to get the total votes before I can calculate the percentage. Following is part of my code.
<?php
$query = "SELECT candidates.CandidateName, candidates.CandidateVotes, candidates.Party, mainrace.MainRaceName, race.RaceName
FROM candidates
JOIN race ON race.RaceID = candidates.RaceID
JOIN mainrace ON mainrace.MainID = candidates.MainID
WHERE candidates.RaceID = 9";
$result = mysql_query($query) or die(mysql_error());
//Loop through db fields.
for($i=0; $row = mysql_fetch_array($result); $i++){
?>
<tr>
<td>Perentage</td>
<td><?php echo $row['CandidateName']; ?></td>
<td><?php echo $row['CandidateVotes']; ?></td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td>Total Votes:</td>
<td>Sum totals</td>
</tr>
At this point I want to be able to run query before this other query and get the
query = "SELECT sum(candidates.CandidateName) FROM candidates WHERE candidates.RaceID =9";
Then I can calculate $Percentage= $CadidateVotes/100;
I appreciate your time and I hope that you have an answer for me. Sincerely
You have several options.
First, you could run a query to get the total number of votes, so then you can divide the candidate's votes by it to get the percentage as you process the query results.
Or you could first process the query results into an array while also adding up total votes, and then process the array. This option requires a bit more code, but should be faster as you do not need to query the database twice.
$candidates=[];
$total_votes=0;
for($i=0; $row = mysql_fetch_array($result); $i++) {
$candidates[$row['name']]['votes'] = $row['votes'];
$total_votes += $row['votes'];
}
foreach ($candidates as $name => $votes) {
$percent = $votes / $total_votes;
?>

sql query to fetch data column wise in php

i have created a table with the name of machine in database.
The columns are
edition, start and stop.
From my form, I am inserting multiple start and stop time for single edition.
like wise there are multiple edition.
How to display all data below edition and loop all the rows for single edition and if edition change then it display in another table.
I want to display reports and reports is refreshing after every 30 sec.
<?php
if (isset($_SESSION['city']))
{
$city = make_safe($_SESSION['city']);
}
$sql = "SELECT Distinct * FROM machine where city = '$city' AND DATE(created) = DATE(NOW())";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
?>
<tr>
<td class="scheduletime"><?php
echo $row["starttime"];
?></td>
<td class="actualtime"><?php
echo $row["stoptime"];
?></td>
<td class="actualtime"><?php
echo $row["Message"];
?></td>
</tr>
<?php
}
?>

How to calculate the SUM of a temp column created from a query

My query is working, but I need to calculate the total of a column which is created from the query, I am using a normal php script to add the value (in money) of the accumulated working hours, this also works perfectly. But how do I then get the Sum or total of this column, which should give me a single figure, used in an echo line as "....accumulated salary for the period is _", see second last line from my script.
Following is a snipped of the script:
<?php
include("../xxx");
$cxn = mysqli_connect($host,$user,$password,$dbname)
or die ("Couldn't connect to server.");
$query = "SELECT
ea.`employee_id`,
e.`employee_surname`,
e.`employee_first_name`,
e.`employee_second_name`,
e.`employee_salary`,
FORMAT((IF((SUM(ea.`empl_attendance_total`))<180,(SUM(ea.`empl_attendance_total`)),180)),1) AS nt,
FORMAT((IF(((SUM(ea.`empl_attendance_total`))-(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)))<=180,
0,(IF(((SUM(ea.`empl_attendance_total`))-(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)))>180,
((SUM(ea.`empl_attendance_total`))-(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)))-180,
0)))),1) AS ot,
FORMAT((IF((SUM(ea.`empl_attendance_total`))>180,
IF((SUM(ea.`empl_attendance_total`))-180>=(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)),
(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)),(SUM(ea.`empl_attendance_total`))-180),
0)),1) AS st,
FORMAT((SUM(ea.`empl_attendance_total`)),1) AS total
FROM
empl_attendance ea
JOIN
employee e
ON ea.`employee_id` = e.`employee_id`
WHERE ea.`empl_attendance_date` BETWEEN '$start_date' AND '$end_date'
GROUP BY `employee_id`";
$result = mysqli_query($cxn,$query)
or die ("Couldn't execute query.");
$total_salary = 0;
/* Displays items already in table */
echo "<table><br>
<tr>
<th>Empl No</th>
<th>Empl Name</th>
<th>N/T (1.0)</th>
<th>O/T (1.5)</th>
<th>S/T (2.0)</th>
<th>Total Hrs</th>
<th>Est Salary</th>
</tr>";
while($row = mysqli_fetch_assoc($result))
{
extract($row);
$sal = ((($employee_salary/180)*$nt)+((($employee_salary/180)*$ot)*1.5)+((($employee_salary/180)*$st)*2));
$salary = number_format($sal, 2, '.', ',');
// add this salary to the total
$total_salary += $sal;
echo "<tr>\n
<td>$employee_id</td>\n
<td>$employee_surname, $employee_first_name $employee_second_name</td>\n
<td>$nt</td>\n
<td>$ot</td>\n
<td>$st</td>\n
<td>$total</td>\n
<td>R $salary</td>\n
</tr>\n";
}
// change the format of the salary variable
$acc_sal = number_format($total_salary, 2, '.', ',');
echo "</table><br>";
echo "Accumulated Salary for the selected period is<b> R $acc_sal<b>";
?>
A fairly easy way of doing this would be to define a new variable (eg $total_salary) before the while loop and adding each salary to it.
So you would have (code is truncated somewhat):
...
$total_salary = 0;
while($row = mysqli_fetch_assoc($result))
{
extract($row);
$sal = ((($employee_salary/180)*$nt)+((($employee_salary/180)*$ot)*1.5)+((($employee_salary/180)*$st)*2));
$salary = number_format($sal, 2, '.', ',');
// add this salary to the total
$total_salary += $sal;
echo "... row markup ...";
}
echo "</table><br>";
echo "<b> Accumulated Salary for the selected period is $total_salary<b>";
P.S.: That's one awesome query!!! :)
Since you're only using GROUP BY on one column, check out the WITH ROLLUP option, which will return you one more row from the database.
If you do this, leave a huge comment in your code, because future developers may not be expecting that extra row.

Categories