I'm very new to coding and trying to learn PHP and MYSQL. What I'm trying to do is, grouping the same CustomerID querys in the same table while making an echo. At the moment, my code echos all the querys seperated. I have a table like
ID CustomerID DATE Company
1 1 2018-11-19 A
2 1 2018-11-19 A
3 2 2018-11-19 B
4 3 2018-11-19 C
5 4 2018-11-19 D
6 4 2018-11-19 D
My code
$query = "SELECT `customers`.ID, `customers`.customerid, `customers`.date
FROM `customers` WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE());
$result = $mysqli->query($query);
while($resultquery = $result->fetch_array())
{
$queryresult[] = $resultquery;
}
if (!empty($queryresult)) {
foreach($queryresult as $queryresults)
{
$id = $queryresults['id'];
$customerid = $queryresults['customerid'];
$date = $queryresults['date'];
?>
Then I echo it and the result is
Company Name: A
ID CustomerID DATE
1 1 2018-11-19
Company Name: A
ID CustomerID DATE
2 1 2018-11-19
Company Name: B
ID CustomerID DATE
3 2 2018-11-19
Company Name: C
ID CustomerID DATE
4 3 2018-11-19
<?php }} ?>
Etc..
But what I want is to compare customerID's and if there is more than one with same id, echo them as a group in the table.
Company Name: A
ID CustomerID DATE
1 1 2018-11-19
2 1 2018-11-19
Company Name: B
ID CustomerID DATE
3 2 2018-11-19
Company Name: C
ID CustomerID DATE
4 3 2018-11-19
I made an sql query with GROUP_CONCAT and used SEPARATOR '|') to group the result, it works but I dont think its the best to achieve this, so please help. Thank you
Map your data in a key-value array with Company as key (include company in the query:
$query = "SELECT customers.ID, customers.customerid, customers.date, company
FROM customers WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE())";
$query = "SELECT `customers`.ID, `customers`.customerid, `customers`.date
FROM `customers` WHERE month(DATE)= month(CURRENT_DATE()) AND YEAR(DATE) = YEAR(CURRENT_DATE());
Then simplify the data collection using a key to group items:
$result = $mysqli->query($query);
$queryresult = [];
while($resultquery = $result->fetch_array())
{
$company = $resultquery['company'];
if (array_key_exists($company,$queryresult){
#$queryresult[$company] = [];
}
#$queryresult[$company][] = $resultquery;
}
An then you can present the information using foreach:
foreach($queryresult as $company => $items){
// header by company
echo "Company Name: $company \n";
echo "ID CustomerID DATE\n";
foreach($items as $item){
// items in company
echo "{$item['id']} {$item['customerid']} {$item['date']}\n";
}
}
Related
Here is the department table
department_id | department_name
1 computers
2 maths
3 physics
4 mba
Here is instructor table
instructor_id | department_id | name
1 1 abc
2 2 manu
3 2 raju
4 3 jaya
5 4 man
From above code how to displays total count of instructors for each department?
what will be the query?
Please help.
I'm doing it in codeigniter.
select d.department_id, count(*) as num_instructors
from departments d
inner join instructors i on i.department_id = d.department_id
group by d.department_id;
You may try to conceptualize from my solution below and see if it can help,
To avoid complication you could just go direct
<?php
//connection
$link = mysqli_connect("localhost","root","","database_name") or die("Couldn't make connection.");
$computer_department_id = //the value
$query = mysqli_query($link, "SELECT department_id FROM instructure_table WHERE department_id='$computer_department_id')");
$total = mysqli_num_rows($query);
echo $total; //this one will display the total number of instructors in computer department
?>
Or if you like
<?php
//connection
$link = mysqli_connect("localhost","root","","database_name") or die("Couldn't make connection.");
$computer_department = //the value
$query = mysqli_query($link, "SELECT department_id
FROM instructure_table AS t
WHERE EXISTS (SELECT department_id
FROM department_table AS d
WHERE d.department_id = t.department_id AND department_id='$computer_department')");
$total = mysqli_num_rows($query);
echo $total; //this one will display the total number of instructors in computer department
?>
So if you place the query in the department line s
department_id | department_name
1 computers //the query
2 maths //the query
3 physics //the query
4 mba //the query
Even if the query for department is in a repeating region it would still work for you. regards
SELECT COUNT(i.instructor_id) as `instructor_count`, d.department_name
FROM instructor AS i
JOIN department ON d.department_id = i.department_id
GROUP BY i.department_id"
I have database table named: timesheets which has the following columns and data:
employee_id employee_name year month day timein timeout department
1 dave 2016 09 15 8 4 finance
1 dave 2016 09 16 8 4 finance
1 dave 2016 09 17 8 4 finance
2 frank 2016 09 15 8 4 purchase
2 frank 2016 09 16 8 4 purchase
which records the daily attendance of employees as you can see above. What I want is to create a payroll report from these attendance records using PHP that shows the total number of working hours for each employee with every department in a separate html table like so:
finance department payroll html table
employe_id | employee_name | total_working_hours
-----------+----------------+---------------------
1 | dave | 24 (8 hrs * 3 days)
purchase department payroll html table
employe_id | employee_name | total_working_hours
-----------+----------------+---------------------
1 | frank | 16
Please note that I don't know the ID's of all employees, so the code should just list everyone grouped by department using PHP / MYSQL
A couple of views will do the job: One for working hours, one for employees, then you can join them and and program your filters, like this:
-- Query the working hours
CREATE VIEW
vw_working_hours
AS
SELECT
employee_id,
year,
month,
SUM((timeout+12) - timein ) AS total_working_hours
FROM
timesheets
GROUP BY
employee_id,
year,
month;
-- Query the employees
CREATE VIEW
vw_employees
AS
SELECT
DISTINCT
employee_id,
employee_name,
department
FROM
timesheets;
-- This query is the actual report
-- just had to filter by department
-- in your script
SELECT
wh.employee_id,
emp.employee_name,
wh.total_working_hours
FROM
vw_working_hours AS wh
JOIN
vw_employees AS emp
ON
wh.employee_id = emp.employee_id
WHERE
wh.year = 2016
AND
wh.month = '09'
AND
emp.department = 'finance';
Or, in a single query (no views):
SELECT
wh.employee_id,
emp.employee_name,
wh.total_working_hours
FROM
(
SELECT
employee_id,
year,
month,
SUM((timeout+12) - timein ) AS total_working_hours
FROM
timesheets
GROUP BY
employee_id,
year,
month
) AS wh
JOIN
(
SELECT
DISTINCT
employee_id,
employee_name,
department
FROM
timesheets
) AS emp
ON
wh.employee_id = emp.employee_id
WHERE
wh.year = 2016
AND
wh.month = '09'
AND
emp.department = 'finance';
In php you should use a loop and an accumulated variable. First you should pre-filter with a query like this:
SELECT
*
FROM
timesheets
WHERE
department = 'finance'
AND
year = 2016
AND
month = '09'
ORDER BY
employee_id;
Then if the result is in a multidimensional array named $rows, something in php like this:
$employee_id = $rows[0]['employee_id'];
$employee_name = $rows[0]['employee_name'];
$accumulated = 0;
foreach($rows as $row) {
$total_working_hours = ($row['timeout'] + 12) - $row['timein'];
if ( $row['employee_id'] == $employee_id ) {
// Same employee, acumulate
$accumulated += $total_working_hours;
} else {
// Another employee, pass the acumulation to result
$rowTmp['employee_id'] = $employee_id;
$rowTmp['employee_name'] = $employee_name;
$rowTmp['total_working_hours'] = $accumulated;
$result[] = $rowTmp;
// Updated the accumulation variables
// new employee
$employee_id = $row['employee_id'];
$employee_name = $row['employee_name'];
// reset accumulated
$accumulated = $total_working_hours;
}
}
// at the end, updates the las result:
$rowTmp['employee_id'] = $employee_id;
$rowTmp['employee_name'] = $employee_name;
$rowTmp['total_working_hours'] = $accumulated;
$result[] = $rowTmp;
// Should pass result to HTML table
print_r( $result );
I have 2 tables in mysql database.
a) company
cid company_name
===================
1 AstraZeneca
2 Emirates
3 Development Bank of Singapore
4 Royal Copenhagen
5 xxx
6 xxx
2) history
hid user_id view_id is_save mark_as view date
==============================================================
1 2 2 0 3 2016-08-25 22:06:12
2 3 3 1 3 2016-08-25 22:07:12
3 3 3 0 1 2016-08-25 22:08:12
4 3 2 0 1 2016-08-25 22:09:12
5 2 4 0 1 2016-08-25 22:10:12
6 4 5 0 1 2016-08-25 22:11:12
7 4 6 0 1 2016-08-25 22:12:12
This view_id is containing cid value.
Now, always I want to show latest 5 company_name from company table as ascending order based on history table view_id.
For that purpose I am doing following query. But company_name is not showing either ASC or DESC order
Here is the query :
$getViewID3 = mysqli_query($link, "SELECT view_id, hid, is_save FROM history WHERE user_id = '$user_id' AND mark_as = 3 GROUP BY view_id ORDER BY view_date DESC LIMIT 5 ");
if(mysqli_num_rows($getViewID3) > 0 ) {
while( $fetchViewId3 = mysqli_fetch_array($getViewID3) ) {
$viewid3 = (int) $fetchViewId3['view_id'];
$hid3 = (int) $fetchViewId3['hid'];
$is_save3 = (int) $fetchViewId3['is_save'];
$getCompany = mysqli_query($link, "SELECT company_name FROM company WHERE cid = '$viewid3' ORDER BY company_name DESC");
if(mysqli_num_rows($getCompany) > 0 ) {
while ($fetchCompany2 = mysqli_fetch_array($getCompany)) {
$cName = htmlspecialchars($fetchCompany2['company_name']);
$url_link = "{$url}company.php?cid=$viewid";
if($is_save3 == 1) {
$checked = 'checked = "checked"';
} else {
$checked = '';
}
echo "<li><a onClick='window.document.location=\"$url_link\"'> $cName </a> <input type='checkbox' class='data_save' $checked data-hid='$hid' data-saveid='$viewid3' name='save_history'></li>";
}
}
}
For example : Result is showing : A, E, D, R, L letter order.
It's should be show : A, D, E, L, R letter Order from company_name column.
If I didn't misunderstand:
SELECT
C.company_name
FROM company C
INNER JOIN
(
SELECT
view_id,
MAX(view_date) max_view_date
FROM history
WHERE is_save IN (0,1) AND mark_as = 3
GROUP BY view_id
ORDER BY max_view_date DESC
LIMIT 5
) AS t
ON C.cid = t.view_id
ORDER BY C.company_name ASC;
Note:
Since you want latest 5 companies the following query will put the last view_date beside the view_id.
Now if you sort these rows based on descending order of max_view_date and later limit the result to 5 then you will get at most five view_ids from the inner query.
Later a simple INNER JOIN between this result set and your company table will finish the job.
Sorry, sorting the final result in ascending order of company name will finish the job.
EDIT:
In order to get all the columns from history table and company_name column from company table:
SELECT
C.company_name,
t.*
FROM company C
INNER JOIN
(
SELECT
history.*
FROM history
INNER JOIN
(
SELECT
view_id,
MAX(view_date) max_view_date
FROM history
WHERE is_save IN (0,1) AND mark_as = 3
GROUP BY view_id
ORDER BY max_view_date DESC
LIMIT 5
) AS latestHistory
ON history.view_id = latestHistory.view_id AND history.view_date = latestHistory.max_view_date
) AS t
ON C.cid = t.view_id
ORDER BY C.company_name ASC;
I have two table which contain have data like as mentioned below:
Table1
TID Name
1 Salman
2 ABC
3 XYZ
Table2
SID STID SUBJECT
1 1 English
2 1 Math
3 2 Physics
4 2 Math
Table1 TID foreign key in Table2 STID. I want to collect data from two table and display in PHP as mentioned below:
Name Subject1 Subject2
Salman English Math
ABC Physic Math
there is my suggestion algorithm
$mysqli = new mysqli("HOST", "USER NAME", "USER PASS", "YOUR DATABASE");
$result = $mysqli->query("SELECT * FROM table1");
while ($row = $result->fetch_assoc()){
$TID = $row['TID'];
$Name = $row['Name'];
$result2 = $mysqli->query("SELECT * FROM table2 where `TTID` = $TID");
echo "$Name \t";
while ($row2 = $result2->fetch_assoc()){
$SUBJECT = $row2['SUBJECT'];
echo "$SUBJECT \t";
}
echo '<br/>';
}
$mysqli->close();
If you know the maximum number of subjects that can be assigned to a student,
Please check this query
SELECT A.Name ,
(SELECT subject from Table2 where STID = A.TID limit 0,1 ) as SUBJECT1,
(SELECT subject from Table2 where STID = A.TID limit 1,1 ) as SUBJECT2
FROM Table1 A
I'm having this PDO query to call data from a MySQL.
$sql = "SELECT itemName FROM furniture WHERE itemID = :item";
While calling for this particular itemName, is it possible to get the next and previous itemNames by using its itemID within this same query itself without having to write a new query to get the next and previous itemNames?
e.g.
if
itemID | itemName
___________________________
553 | Mahogani Black Chair
554 | Teak Round Table
555 | Thulang Relaxing Chair
556 | Teak Relaxing Chair
$sql = "SELECT itemName FROM furniture WHERE itemID = :item";
$stmt = $connect->prepare($sql);
$stmt->execute(array(':item'=>"554"));
$rslt = $stmt->fetchAll(PDO::FETCH_ASSOC);
I'm looking away of getting Teak Round Table and Mahogani Black Chair and Thulang Relaxing Chair
Please use this code:
(SELECT itemName FROM furniture WHERE itemID < 554 order by itemID desc limit 1)
UNION
(SELECT itemName FROM furniture WHERE itemID >= 554 order by itemID asc limit 2)
For Example code :
MyTable:
================
id Store_name
================
1 English
2 French
3 Tamil
4 Uk
5 US
<?php
$con = mysqli_connect("localhost","root","ramki","ramki");
$sql = "(SELECT store_name FROM store WHERE id < 2 order by id desc limit 1)
UNION
(SELECT store_name FROM store WHERE id >= 2 order by id asc limit 2)";
$query = mysqli_query($con,$sql);
while ($row = mysqli_fetch_assoc($query)) {
echo $row['store_name'];
echo "<br>";
}
?>
$sql = "SELECT itemName FROM furniture WHERE itemID IN (:item-1, :item, :item+1) ORDER BY itemID";
For iterating the results, you can also use PDO fetch() function to get each row.