MYSQL select from table and count from another - php

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";

Related

counting occurrences of certain inputs in data table/database

I am currently populating a data table on my website from information stored in a mysql database
The table is of the form:
Table 1
ID | DataA | Other Info | Count Data
======================================
1 | A | Other Info | 2
2 | B | Other Info | 3
Table 2
ID | Input
==========
1 | A
2 | A
3 | B
4 | B
5 | B
Count data in table 1 is intended to show how often the entry form the DataA column appears in the input column in Table2
Update....
CREATE TABLE driver (
`ID` INTEGER,
`DataA` VARCHAR(1),
`Other Info` VARCHAR(10),
primary key (ID)
);
$sql = "SELECT * FROM `driver` ORDER BY drivercompany";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while ($result = mysqli_fetch_assoc($query)) {
echo "<tr>
<td class='class'>" . $result['id'] . "</td>
<td>" . $result['DataA'] . "</td>
<td>" . $result['otherinfo'] . "</td>
<td></td> /**count goes here**/
</tr>";
}
}
?>
using db fiddle, the query I need to get the count is:
SELECT driver.*, COUNT(add_job.Input) AS counter
FROM driver
LEFT JOIN add_job ON add_job.Input = driver.DataA
GROUP BY driver.ID
I have tried adding it to my code as so:
$sql = "SELECT * FROM `driver` ORDER BY drivercompany";
$query = mysqli_query($conn, $sql);
$count = "SELECT `driver`.*, COUNT(`add_job`.`adddriver`) AS counter
FROM `driver`
LEFT JOIN `add_job` ON `add_job`.`adddriver` = `driver`.`drivercompany`
GROUP BY `driver`.`id`";
$counter = mysqli_query($conn, $count);
while($result = mysqli_fetch_assoc($query,$counter)) { //and other variations
I cannot determine how to get $count and $query to work together
You can JOIN the two tables, group by the primary key of table1 and count the number of occurances in table2 with a single query.
Assuming ID is the primary key in table1, change your query to:
$sql = "
SELECT t1.*, COUNT(t2.Input) AS counter
FROM table1 t1
LEFT JOIN table2 t2 ON t2.Input = t1.DataA
GROUP BY t1.ID
";
The result would be:
| ID | DataA | Other Info | Count Data | counter |
| --- | ----- | ---------- | ---------- | ------- |
| 1 | A | Other Info | 2 | 2 |
| 2 | B | Other Info | 3 | 3 |
See the result in db-fiddle
Then you can use $result['counter'] in your output. Eg.:
echo "
<tr>
<td class='class'>{$result['id']}</td>
<td>{$result['DataA']}</td>
<td>{$result['otherinfo']}</td>
<td>{$result['counter']}</td>
</tr>
";
Note: If you have the ONLY_FULL_GROUP_BY mode enabled in MySQL < 5.7 or any version of MariaDB, the query will raise an error. In this case you should change it to
SELECT t1.id, t1.DataA, t1.otherinfo, COUNT(t2.Input) AS counter
FROM table1 t1
LEFT JOIN table2 t2 ON t2.Input = t1.DataA
GROUP BY t1.id, t1.DataA, t1.otherinfo
To include all selected non-aggreagted columns in the GROUP BY clause.

PHP SQL Query That Displays Certain Results Based On Values In Another Table

Right now, I have two database tables. Table history_2014 has a column(member) that says whether or not a member is active (Y or N). I have another table called history_overall that contains all of the contact information for these members. I need a table that will only show the rows of history_overall for active members. Right now, I have this PHP:
<?php
$con=mysqli_connect("localhost","myusername","mypassword","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM history_overall");
echo "<table border='1'>
<tr>
<th>Address 1</th>
<th>Last Name</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['address1'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The current code will allow me to display all rows, but I need to be able to display certain rows based on the other table.
what column ties the two tables together?
A JOIN will accomplish this if there is a relationship.
Example:
SELECT history_overall.* FROM members
JOIN history_overall
ON history_overall.member_id = members.id
WHERE members.active = 'Y';
----Edit/Comment----
Since I'm not able to add the table structure layout in a comment I will comment here.
It is more valuable when wanting to retrieve specific records from the database to provide us with the table schema as opposed to the actual table names. As well as an example of the resulting data you want as a result.
All you really provided to us with is table history_2014 with columns (member = Y|N), table history_overall with columns (address1, last_name) which doesn't allow us to build a relationship between the two (or more) tables.
Here is an example assuming both tables have a memberid column:
----------------------- -------------------------------------
| table1 | | table2 |
----------------------- -------------------------------------
| member | memberid | | address1 | full_name | memberid |
----------------------- -------------------------------------
| Y | 1 | | 123 street | jon doe | 1 |
----------------------- -------------------------------------
| N | 2 | | 789 court | jane doe | 2 |
----------------------- -------------------------------------
| Y | 3 | | 456 road | foo bar | 3 |
----------------------- -------------------------------------
Question: How can I retrieve records from table2 where the member in table1 is 'Y'?
This is my desired result of the records:
-------------------------------------
| recordset |
-------------------------------------
| address1 | full_name | memberid |
-------------------------------------
| 123 street | jon doe | 1 |
-------------------------------------
| 456 road | foo bar | 3 |
-------------------------------------
Answer query:
SELECT table2.*
FROM table1
JOIN table2
ON table1.memberid = table2.memberid
WHERE table1.member = 'Y'
Explained:
Retrieve all columns in table2 that the memberid column in table1 is the same as the memberid column in table2 from the rows in table1 that the member column contains Y as a value with no ordering or limit on the amount of records returned.
I guess you have some kind of Id of the user in both tables, you could make a query creating a join between the two tables where id matches and selecting only the rows where member = 'Y'
Simply use this method
select * from history_overall,members where members.status='active'
You will get all the active members results including history also.
Use a table join (MySQL doc: http://dev.mysql.com/doc/refman/5.7/en/join.html).
In short, something like:
SELECT ho.*
FROM history_overall AS ho
RIGHT JOIN history_2014 AS h ON ho.memberId = h.memberId
WHERE h.isActive = 'Y';
Obviously your field names are probably different...

Sorting an array of information from another array output from SQL

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>";
?>

how to update by IdItem

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'")

Split up array into rows

I have a table, with values from dat_eb_registrants as rows (e.g. $row[1]) and values from a horizontal array, extracted from dat_eb_field_values, I'd like to split those up so I can order everything into the table how I want it.
How the data gets put into my table:
$count = 0;
while ($row = mysql_fetch_row($result))
{
echo "<tr>";
$myArray[] ="<tr><td>" . $row[9] . "</td><td>"; echo $myArray[$count];
$count++;
echo "</tr>";
}
How all of the data get extracted from the database (yes, I know it's old):
SELECT dr.id, dr.first_name, dr.last_name, dr.email, dr.comment, dr.amount, dr.published, dr.transaction_id, dr.register_date, GROUP_CONCAT(df.field_value SEPARATOR '</td><td>')
FROM dat_eb_registrants dr
LEFT JOIN dat_eb_field_values df
ON dr.id=df.registrant_id
WHERE `event_id` >= 20 AND `event_id` <= 25
GROUP BY dr.id
ORDER BY '".$sort."', '".$ascdsc."'
Now, I want to put some rows from the first table (e.g. $row[1]) and (.eg. $row[2]) vertically, in the middle of the array. How can I do this?
Because the array fills my table in one time, and using the $rows, you can simply tell which rows to display where...
This is what I want (code might not be correct):
while ($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>"'.$row_table_1[1]'"</td>";
echo "<td>"'.$row_table_1[2]'"</td>";
echo "<td>"'.$row_table_2[35]'"</td>";
echo "<td>"'.$row_table_2[45]'"</td>";
echo "<td>"'.$row_table_1[5]'"</td>";
echo "<td>"'.$row_table_2[6]'"</td>";
echo "</tr>";
}
I used to do:
echo "<td>"; $result24 = mysql_query("SELECT field_id, field_value FROM dat_eb_field_values WHERE (field_id = 88) AND (registrant_id = $row[0])"); $r24 = mysql_fetch_row($result24); echo $r24[1]; echo "</td>";
echo "<td>"; $result25 = mysql_query("SELECT field_id, field_value FROM dat_eb_field_values WHERE (field_id = 57) AND (registrant_id = $row[0])"); $r25 = mysql_fetch_row($result25); echo $r25[1]; echo "</td>";
echo "<td>" . $row[5] . "</td>";
echo "<td>" . $row[6] . "</td>";
I want to do:
echo "<td>" . $rowfromsecondtable[1] . "</td>";
echo "<td>" . $rowfromsecondtable[2] . "</td>";
echo "<td>" . $row[5] . "</td>";
echo "<td>" . $row[6] . "</td>";
(using the code I gave above)
Preview of dat_eb_registrants:
| id | first_name | last_name | email |
------------------------------------------------------------------------
| 1 | Mike | Doe | mikedoe#hotmail.com |
| 2 | John | Smith | j_smith#hotmail.com |
Preview of dat_eb_field_values:
field 1 = fav.sport
field 2 = fav. color
field 3 = fav. food
| registrant_id | field_id | field_value |
----------------------------------------------------------
| 1 | 1 | tennis |
| 1 | 2 | green |
| 1 | 3 | spagetti |
| 2 | 1 | hockey |
| 2 | 2 | red |
| 2 | 3 | fish |
I need:
first_name | id | fav.sport | last_name | fav.food |
---------------------------------------------------------------------
Mike | 1 | Tennis | Doe | spagetti |
John | 2 | Hockey | Smith | fish |
Maybe I am missing something but why not just perform this task in SQL. This is basically a pivot. MySQL does not have a pivot but you can use an aggregate function with a CASE statement:
select r.first_name,
r.id,
r.last_name,
max(case when f.field_id =1 then f.field_value else null end) As FavSport,
max(case when f.field_id =2 then f.field_value else null end) As FavColor,
max(case when f.field_id =3 then f.field_value else null end) As FavFood
from dat_eb_registrants r
left join dat_eb_field_values f
on r.id = f.registrant_id
group by r.first_name, r.id, r.last_name
order by r.id
See SQL Fiddle with Demo
The result of the query is the output that you want:
| FIRST_NAME | ID | LAST_NAME | FAVSPORT | FAVCOLOR | FAVFOOD |
----------------------------------------------------------------
| Mike | 1 | Doe | tennis | green | spagetti |
| John | 2 | Smith | hockey | red | fish |
Or you can use multiple joins on the dat_eb_field_values table:
select r.first_name,
r.id,
r.last_name,
fSport.field_value FavSport,
fColor.field_value FavColor,
fFood.field_value FavFood
from dat_eb_registrants r
left join dat_eb_field_values fSport
on r.id = fSport.registrant_id
and fSport.field_id = 1
left join dat_eb_field_values fColor
on r.id = fColor.registrant_id
and fColor.field_id = 2
left join dat_eb_field_values fFood
on r.id = fFood.registrant_id
and fFood.field_id = 3
order by r.id
See SQL Fiddle with Demo. It produces the same result.
This does not answer your question but instead of using $row[9], $row[10] etc, you can just use the column names of your table as the row index.
$row['first_name']
$row['last_name']
and so on. It'll make your code more readable.
You might also want to grab all your data at first and then generate your html code. It'll look cleaner.
e.g
$result24 = mysql_query(sometihng here);
$r24 = mysql_fetch_row($result24);
$result25 = mysql_query(sometihng else here);
$r25 = mysql_fetch_row($result25);
//php code for table starts here
echo '<table>';

Categories