I have a script which retrieves all users with the same "dealership_id" from the "users" table, this works fine. Each user within these records has an ID (users_sales_guild_id) which is also on another table called "sales_list".
What I am trying to do is list the total amount of sales which each user has from the "sales_list" table next to the respective user
Currently it prints the logged in user's amount (John Smith , value of 5), and not each individual amount, where am I going wrong?
How I would like it to look
Name | Position | SID | Total Sales |
John Smith | Sales Consultant | 23434 | 5 | Details
Jane Smith | Sales Consultant | 34234 | 9 | Details
John Chan | Sales Manager | 43423 | 3 | Details
Jane Chan | Sales Consultant | 23344 | 7 | Details
How it looks
Name | Position | SID | Total Sales |
John Smith | Sales Consultant | 23434 | 5 | Details
Jane Smith | Sales Consultant | 34234 | 5 | Details
John Chan | Sales Manager | 43423 | 5 | Details
Jane Chan | Sales Consultant | 23344 | 5 | Details
PHP Code
$query = "SELECT `users_id`, `users_email` , `users_sales_guild_id` , `users_dealer_code_id` ,
`users_first_name` , `users_surname` , `users_dealer_name` , `users_type` , DATE_FORMAT(`registration_date`, '%d-%m-%Y')
AS `dr`
FROM `users`
WHERE `dealership_id` = '".$_SESSION['dealership_id']."'
AND (users_type = 'Sales Manager' OR users_type = 'Sales Consultant')
ORDER BY registration_date DESC";
$result = mysql_query("SELECT * FROM sales_list WHERE sales_list.users_sales_guild_id ='" . $_SESSION['users_sales_guild_id'] . "'");
$num_rows = mysql_num_rows($result);
$result = #mysql_query ($query); // Run the query.
echo '<table>
<tr>
<td align="center">Name</td>
<td align="center">Position</td>
<td align="center">ID</td>
<td align="center">Total Sales</td>
<td align="center"></td>
</tr>';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#e1e3e6' ? '#cdcdcf' : '#e1e3e6'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="center">' . $row['users_first_name'] . ' ' . $row['users_surname'] . ' </td>';
echo '<td align="center">' . $row['users_type'] . '</td>';
echo '<td align="center">' . $row['users_sales_guild_id'] . '</td>';
echo '<td align="center">' . $num_rows . '</td>';
echo '<td align="center"><a href="sm-sales-ind-2.php?smid=' . $row['users_id'] . '">Details</td>';
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
?>
You'd have to add a subquery or join to your sql, something similar to:
Join:
SELECT name, COUNT(sales_list.*)
FROM salesman
JOIN sales_list ON salesman.id = sales_list.salesman_id
GROUP salesman.id
Subquery:
SELECT
name,
(SELECT COUNT(*) FROM sales_list
WHERE salesmen.id = sales_list.salesman.id) as sales_count
FROM salesmen
Then you can use $row['sales_count'] in the output
The $num_rows refers to the number of rows returned, it doesn't contain any specific counts of sales per user
Related
I have 3 tables from Microsoft Access database that I want to query. But I only manage to query 2 tables which is easier because 2 tables have relationship between primary key and foreign key in those 2 tables.
Table tblEmployee
Employee ID | Employee Name | Department ID |
1 | A | AS1 |
2 | B | CEO |
3 | C | AS2 |
Table tblDepartment
Department ID | Department |
CEO | Chairman |
AS1 | Assistant1 |
AS2 | Assistant2 |
Table tblPAyTransTemp
Employee ID | Payment |
1 | 50.00 |
2 | 80.00 |
3 | 30.00 |
Here is my code:
$sql = "SELECT `Employee ID` AS `No`,
(
SELECT `Employee Name`
FROM `tblEmployee`
WHERE `Employee ID` = tblPAyTransTemp.`Employee ID`
) AS `Name`,
(
SELECT `Department`
FROM `tblDepartment`
WHERE `Department ID` = tblEmployee.`Department ID`
) AS `Department`,
`Payment`
FROM `tblPAyTransTemp`
WHERE `Month` ='$month' AND `Year` ='$year'
ORDER BY `Employee ID` ASC";
if ($result = $connectdb->query($sql))
{
$totalPayment = 0;
echo '<table>'
. '<th>No</th>'
. '<th>Name</th>'
. '<th>Department</th>'
. '<th>Payment</th>'
. '</tr>';
foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row)
{
echo '<tr>'
. '<td>' . $row["No"] . '</td>'
. '<td>' . substr($row["Name"], 0, 50) . '</td>'
. '<td>' . $row["Department"] . '</td>'
. '<td>' . number_format((float)$row["Payment"], 2, '.', '') . '</td>'
. '</tr>';
$totalPayment += $row["Payment"];
}
echo '<tr>'
. '<td colspan="3">Total</td>'
. '<td>' . number_format((float)$totalPayment, 2, '.', '') . '</td>'
. '</tr>'
. '</table>';
}
How to display like this?
No | Name | Department | Payment |
2 | B | Chairman | 80.00 |
Assistant | |<---subheader for each department
1 | A | Assistant1 | 50.00 |< list of subheader
3 | C | Assistant2 | 30.00 |< list of subheader
Total | 160.00 |
I have subjects table contains subjects details and subject_student table contains the subjects selected by students. I want to select all the the subjects details selected by more than 2 students and also get the count of students for each subject selected by more than 2 students.
Subjects table
------------------------------
ID | Name | units
------------------------------
1 | web | 1
2 | programming | 1
3 | java | 1
4 | QA | 1
------------------------------
student_subject Table
Subject table
------------------------------
student_id | subject_id | status
------------------------------
1 | 1 | current
1 | 2 | current
2 | 1 | current
2 | 3 | current
3 | 1 | current
3 | 3 | current
4 | 1 | current
5 | 5 | current
------------------------------
so the result here must select the first row of subjects table and the 4 which is the count of students selected web subject
Here is the Query:
$query= "
SELECT s.sub_ID
, s.Name
, s.units
, count(st.subject_id) as cc
from subjects as s
LEFT
JOIN students_subject as st
ON s.ID = st.subject_id
GROUP
BY st.subject_id
Having count(st.subject_id)>2)
";
when I run the code it gives me this error:
Notice: Trying to get property of non-object
here is the PHP code:
global $con,$users;
$query= "SELECT s.sub_ID,s.Name, s.units,s.dept, count(st.subject_id)as cc from subjects as s LEFT JOIN students_subject as st
ON s.ID=st.subject_id GROUP BY st.subject_id Having count(st.subject_id)>2)";
//$query="SELECT * FROM subjects;";
$result=mysqli_query($con,$query);
if ( $result->num_rows == 0 ) // User doesn't exist
echo "Subjects doesn't exist!";
else { echo "
<tr>
<th>Subjects ID</th>
<th>Title</th>
<th>Units</th>
<th>Department</th>
<th>Check</th>
</tr>";
$r=0;
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['sub_ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['units'] . "</td>";
echo "<td>" . $row['cc'] . "</td>";
}
Check your query for names of tables and columns Subjects(ID,Name,units), students_subject(student_id,subject_id,status):
SELECT
sb.id AS sub_ID, -- !!!
sb.Name,
sb.units,
COUNT(st.student_id) AS cc
FROM Subjects sb
JOIN students_subject st ON st.subject_id=sb.id
GROUP BY sb.id,sb.name,sb.units
HAVING COUNT(st.student_id)>2
You also can use print_r in while for test names which were returned with mysqli_fetch_array
while($row = mysqli_fetch_array($result))
{
print_r($row);
...
Here doesn't need a bracket )
$query= "... Having count(st.subject_id)>2)"; // <--
Try to delete it
$query= "... Having count(st.subject_id)>2";
I need to be retrieve multiple unique values from an array set of data. Currently they are extracted as follows :
while($row1 = mysql_fetch_array($result1))
{
echo "<tr>".
"<td>".$row1[0] . "</td>".
"<td>".$row1[1] . "</td>".
"<td>".$row1[2] . "</td>".
"<td>".$row1[3] . "</td>".
"<td>".$row1[4] . "</td>".
"<td>".$row1[5] . "</td>".
"<td>".$row1[6] . "</td>".
"<td>".$row1[7] . "</td>".
//$row1[8] is the number of hours
"<td>".$row1[8] . "</td>".
//$row1[9] is the user
"<td>".$row1[9] . "</td>";
}
As commented above, I need to accumulate the hours per user. However, I have problem sorting the array as the user value has to be unique in the array whereas the number has to keep stacking.
Really confused now. Appreciate any help offered.
EDIT : $row1[8] is an integer yes.
The sample data output table ( sorry no image) will be as follows :
------------------------------------------------------------------------------------------
Users |Telephone | Address | Postal Code | Hobbies | Interest| FB |Twitter | Insta | Hours
------------------------------------------------------------------------------------------
John | 92238726 | SG | 345322 | Running | Movies | 1 | 0 | 0 | 5
Tom | 922382134 | MY | 345212 | Soccer | Movies | 1 | 0 | 0 | 8
Jerry | 92238726 | SG | 342122 | stamps | Nil | 0 | 1 | 0 | 5
John | 92238726 | SG | 345322 | Running | Movies | 1 | 0 | 0 | 12
Jerry | 92238726 | SG | 342122 | stamps | Nil | 0 | 1 | 0 | 2
Based on the output above which was extracted with the mysql_fetch_array, I'd like to sort the information to something like the following :
Users | Total Hours
John | 17
Tom | 8
Jerry | 7
SQL CODE :
"select DISTINCT jl.refno, jl.logno, jl.attendee, jl.jobsummary, FROM_UNIXTIME(jl.date, '%d/%m/%y') AS 'Date-In', from_unixtime(jl.dateout + (15*3600), '%d/%m/%y') AS 'Date-Out', #timein := (left(jl.timein,2)*60+right(jl.timein,2)) AS 'Time-In', #timeout := (left(jl.timeout,2)*60+right(timeout,2)) AS 'Time-Out', #temp := ((dateout -date)* 24 * 60) + #timeout - #timein AS 'temp', us.username from joblog jl, projects proj, users us where jl.project ='{$value}' AND proj.id ='{$value}' AND jl.staff = us.id"
Since you are using MySQL anyway, I recommend you to do it with an SQL. It's cleaner.
Edit your query to:
SELECT users, SUM(hours) as total FROM userTable GROUP BY users ORDER BY total DESC;
UPDATE - PHP Edition:
You can do it like this in PHP.
$counters = array();
while ($row1 = mysql_fetch_array($result1)) {
$counters[$row1[9]] += $rows1[8];
}
arsort($counters);
foreach ($counters as $name => $total) {
// do your output here
}
<?php
function totalHours($user){
$result=mysql_query("select sum(hours) as total from table_name where users='".$user."'");
$row=mysql_fetch_array($result);
return $row['total'];
}
$result=mysql_query("select * from table_name group by users");
echo "</table>";
echo "<tr>
<td>User</td>
<td>Total Hours</td>
</tr>";
while($row1 = mysql_fetch_array($result1))
{
echo "<tr>".
"<td>".$row1[0]. "</td>".
"<td>".totalHours($row1[0]). "</td></tr>";
}
echo "</table>";
?>
I have put a script together which prints all of the rows from the "sales_list" table but only those with the "users_sales_guild_id" which matches the logged in user. This works fine.
What I am trying to do is print all of the rows but retrieve the matching sales_id from the "accessories_orders" table, and put the "accessories_orders_total" and shipped status with the query, so the query below should look like this in the browser if the person logging in has a "user_sales_guild_id" value of "1234".
+--------+---------------+-------------------+----------+
| Model | Customer Name | Accessories Total | Status |
+--------+---------------+-------------------+----------+
| Nissan | Malcom Smith | | Add |
| Ford | Jane Smith | 200.00 | Pending |
+------------------------+-------------------+----------+
So if there is a matching row in the "accessories_orders" table, then it will print the "shipped" and "accessories_orders_total" data. If there is no matching row for this, then it will display an "Add" link which leads to the add_accessories_sales.php.
I'm getting an error message "Undefined index: sales_model" and pretty much everything else within the first query, can anyone point out where I am going wrong?
"sales_list" Table
+--------------------------------------------------------------------------------------------------------------------------+
| sales_list |
+------+--------------------------+--------------------------+------------------------+-------------+----------------------+
| sales_id | users_sales_guild_id | sales_customer_firstname | sales_customer_surname | sales_model | sales_entry_date |
+----------+----------------------+--------------------------+------------------------+-------------+----------------------+
| 1 | 1234 | Jane | Smith | Ford | 2013-12-02 12:00:00 |
| 2 | 5678 | John | Chan | Mazda | 2013-12-03 12:00:00 |
| 3 | 5678 | Kevin | Chan | Fiat | 2013-12-04 12:00:00 |
| 4 | 1234 | Malcom | Smith | Nissan | 2013-12-05 12:00:00 |
+----------+----------------------+--------------------------+------------------------+-------------+----------------------+
"accessories_orders" table
+-------------------------------------------------------------------------------------------------------------------------+
| accessories_orders |
+-----------------------+----------------------+----------+--------------------------+-------------------------+----------+
| accessories_orders_id | users_sales_guild_id | sales_id | accessories_orders_total | accessories_orders_date | shipped |
+-----------------------+----------------------+----------+--------------------------+-------------------------+----------+
| 1 | 1234 | 1 | 200.00 | 2013-12-02 12:00:00 | Pending |
| 2 | 5678 | 2 | 350.00 | 2013-12-03 12:00:00 | Pending |
| 3 | 5678 | 3 | 100.00 | 2013-12-03 12:00:00 | Pending |
+-----------------------+----------------------+----------+--------------------------+-------------------------+----------+
EDITED and UPDATED Code
<?php
require_once ('database.php'); // Connect to the database.
$query = " SELECT sl.sales_model, sl.sales_customer_firstname, sl.sales_customer_surname, ao.accessories_orders_total, ao.shipped,
COALESCE(ao.shipped)
FROM sales_list sl
LEFT JOIN accessories_orders ao ON(ao.sales_id = sl.sales_id)
WHERE sl.users_sales_guild_id ='".$_SESSION['users_sales_guild_id']."'
ORDER BY
".$order_by." LIMIT ".$start.", ".$display;
$result = #mysql_query ($query); // Run the query.
echo '<table width="610" cellspacing="1" cellpadding="5" style="font-size:11px;">
<tr>
<td align="center">Model </td>
<td align="center">Customer Name</td>
<td align="center">Accessories Total</td>
<td align="center">Status</td></tr>';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$status = $row['shipped'];
$bg = ($bg=='#e1e3e6' ? '#cdcdcf' : '#e1e3e6'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="center">' . $row['sl.sales_model'] . '</td>';
echo '<td align="center">' . $row['sl.sales_customer_firstname'] . ' ' . $row['sl.sales_customer_surname'] . '</td>';
echo '<td align="center">$' . $row['acc.accessories_orders_total'] . '</td>';
$str = '<td align="center">';
if($status == 'Pending') {
$str .=' Pending</td></tr>';
}
else {
$str .='<strong>Add</strong></td></tr>';
}
echo $str;
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); //Close the database connection.
?>
Your query needs to be more like this:
SELECT sl.sales_model, sl.sales_customer_firstname, sl.sales_customer_surname, ao.accessories_orders_total, COALESCE(ao.shipped, 'Add') status
FROM sales_list sl
LEFT JOIN accessories_orders ao ON(ao.sales_id = sl.sales_id)
WHERE sl.users_sales_guild_id = 1234;
The LEFT JOIN is the key here. It allows a row to be returned with the data from sales_list even if there is no corresponding entry in accessories_orders.
See this fiddle for a working example: http://sqlfiddle.com/#!2/f7d3d/4
As others have already stated, you should be using the mysqli function set as opposed to the mysql function set.
First, you should not be including the table names. Example:
//wrong
echo '<td align="center">' . $row['sl.sales_model'] . '</td>';
//correct
echo '<td align="center">' . $row['sales_model'] . '</td>';
Second, you should not be using mysql unless you are using an outdated version of PHP. Switch to mysqli or PDO.
Third, you have no error handling to tell you whether your query is successful or not. In fact, you have the opposite of error handling, because you are trying to use the # operator to suppress your errors. Instead, you should do something like this:
//assuming you switch to mysqli
mysqli_query("SELECT acc.accessories_orders_id, acc.users_id, acc.sales_id,
acc.accessories_orders_total, acc.accessories_orders_date, acc.shipped,
acc.timestamp, sl.sales_id
FROM accessories_orders AS acc, sales_list AS sl
WHERE acc.sales_id = sl.sales_id");
if(mysqli_error()) {
throw new Exception(mysqli_error(), mysqli_errno());
}
If you do this, your mysql errors will be logged in the same place as your php errors. You will then be able to tell whether any of your trouble is coming from the query being malformed.
To master2 in php, mysql. I'm new in php about 2 month
I need help. about update table.
I have page that display current table. when I click update button update, I want row 1, quantity in current table will decrease by IdItem from result table. So the equation will like this in current table quantity=quantity-quantityPass. So only field Item change quantity result. Now when I click update, it effect to all in table current result. any solution?
table for 'result'
+--------+-------------+--------------+-----------+--------+--------------+
| IdItem | username | rentItem | quantity | result | quantityPass |
+--------+-------------+--------------+-----------+--------+--------------+
| 84 | FahmiNazirul| Speaker | 1 | PASS | 1 |
+--------+-------------+--------------+-----------+--------+--------------+
| 86 | Andy | Keyboard | 3 | PASS | 2 |
+--------+-------------+--------------+-----------+--------+--------------+
| 89 | FahmiNazirul| Speaker | 5 | PASS | 3 |
+--------+-------------+--------------+-----------+--------+--------------+
table for current quantity 'update'
+--------+-------------+--------------+
| Id | Item | quantity |
+--------+-------------+--------------+
| 1 | Speaker | 10 |
+--------+-------------+--------------+
| 2 | Keyboard | 10 |
+--------+-------------+--------------+
tableupdate.php
$result = mysql_query("SELECT * FROM update where Item = Item");
echo "<table border='1'>
<tr>
<th>Item</th>
<th>Quantiti</th>
<th></th>
</tr>";
while($row = mysql_fetch_array($result))
{
$item= $row['Item'];
echo " <tr> ";
echo " <td> " . $row['Item'] . " </td> ";
echo " <td> " . $row['quantity'] . " </td> ";
echo " </tr> ";
}
echo "</table>";
echo " <a href ='quantityupdate.php?Item=$item' onclick='return Confirm_Box()' >Update</a>";
quantityupdate.php
$item =$_REQUEST['Item'];
// sending query
mysql_query("UPDATE update ,result SET update.quantity=update.quantity-result.quantityPass where update.Item = result.rentItem")
or die(mysql_error());
header("Location: update.php");
Use UPDATE with JOIN like this:
UPDATE kemaskini AS u
INNER JOIN result AS r ON u.Item = r.rentItem
SET u.quantity = u.quantity - r.quantityPass;
For the duplicate entries of the Item in the first table result you can do this:
UPDATE kemaskini AS u
INNER JOIN
(
SELECT rentItem, SUM(quantityPass) AS TotalquantityPass
FROM result
GROUP BY rentItem
) AS r ON u.Item = r.rentItem
SET u.quantity = u.quantity - r.TotalquantityPass;
SQL Fiddle Demo
mysql_query("UPDATE update ,result SET update.quantity=update.quantity-result.quantityPass where result.rentItem='$item' AND update.Item='$item'")