I can't seem to find the right way to do this so I was hoping someone could give me some direction?
The SQL Database is structured like this (I've removed the irrelevant stuff):
Requests
R_ID R_FulfilledBy
1 Bob
2 Craig
3 Bob
SIMs
SM_ID SM_FulfilledBy
1 Bob
2 Craig
3 Bob
I'm hoping to end up with this output:
Fulfilled By Requests
Bob 4
Craig 2
Here's my PHP/HTML:
<div id="table">
<?php
//Connect to MySQL Database
$connection = mysql_connect($runnerdbServer, $runnerdbUser, $runnerdbPass);
mysql_select_db($runnerdbName, $connection) or die("MysQL Error");
$query = "SELECT R_FulfilledBy, COUNT(R_ID) FROM Requests GROUP BY R_FulfilledBy ORDER BY COUNT(R_ID) DESC";
$result = mysql_query($query) or die(mysql_error());
?>
<!-- Number of Runners (Counts total number of records in Requests table) -->
<table border='0' width='50%'>
<tr>
<th>Runners Fulfilled</th>
<tr><td><?php
$query = mysql_query("SELECT * FROM Requests");
$number=mysql_num_rows($query);
echo $number;
?>
</td></tr>
</table>
<!-- Fulfillment Stats -->
<table border='0' width='50%'>
<tr>
<th>Name</th>
<th>Runners Fulfilled</th>
</tr>
<?
// Print out result (I want this to calculate requests fulfilled by each user in 'Requests' and 'SIMs' table)
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>". $row['R_FulfilledBy'] ."</td>";
echo "<td>". $row['COUNT(R_ID)'] ."</td>";
echo "</tr>";
}
?>
</table>
At present it's only calculating the records from the 'Requests' table :(
You could union all the two tables together in a subquery:
select FulfilledBy
, count(*)
from (
select R_FulfilledBy as FulfilledBy
from Requests
union all
select SM_FulfilledBy
from SIMs
) as SubQueryAlias
group by
FulfilledBy
Use union all instead of union because the second eliminates duplicates; which would give everyone a maximum count of 1.
I'd go with this:
SELECT R_FulfilledBy, COUNT(*) +
( SELECT COUNT(*) FROM SIMs WHERE R_FulfilledBy = SM_FulfilledBy )
FROM Requests GROUP BY R_FulfilledBy
Related
Alright so i need to post the top 3 business categories with the top searches. I've tried the advice provided to be online:
$sql = "select search, city, business, count(*)
from vendor
group by category = 'Beauty Salon'
order by count(*) desc
fetch first 3 rows only";
I've tried:
$sql = "SELECT search, city, business,
COUNT(*) AS total FROM vendor
WHERE category = 'Beauty Salon' GROUP BY ASC LIMIT 3";
I've had others but to be honest I've tried it in so many ways i can't remember the sources.
I hope you can help me with this. Thank you!
Here is the full code i have been trying maybe it has nothing to do with the sql, but what comes afterwards.
<?php
include '../s.php';
$sql = "SELECT search, city, business, COUNT(*) AS total FROM vendor WHERE category = 'Beauty Salon' GROUP BY ASC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{ ?>
<table class="demo">
<thead>
<tr class="titledemo" align="left">
<th width="25%">Ranking</th>
<th width="25%">Business</th>
<th width="25%">Searches</th>
<th width="25%">Category</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<? echo "<strong>" . $row["business"]. "<br></strong>";?>
</td>
<td>
<? echo "" . $row["search"]. "<br>";
?>
</td>
<td>
<? echo "" . $row["city"]. "<br>"; ?>
</td>
</tr>
</tbody>
</table>
<?
}
} else {
echo "0 results";
}
$conn->close();
?>
NOTE: when it did show before it would not align the rows from the top the least. It is showing 100, 200, 300 and not 300, 200, 100. I do believe that it is grabbing the top to lest by the date it was inserted because that is how the numbers are set in my database. I didn't understand since I've tried DESC and ASC and none showed what i needed. It should be based on search since that's the number amount of searches for each company.
You need a subquery first before limiting your results.
select * from (select search, city, business, count(*) ct
from vendor
where category = 'Beauty Salon'
group by search, city, business) t
order by ct asc
limit 3
Try this :
SELECT search, city, business,
COUNT(*) AS total FROM vendor
WHERE category = 'Beauty Salon' and ROWNUM <=3
try "TOP 3" after SELECT.
SELECT TOP 3 search, city, business
FROM vendor
GROUP BY category = 'Beauty Salon'
I can count number of a table rows by using mysqli_num_rows. I have a table which contains similar rows. How can I count by grouping by similar row?
For instance: I have a table with 2 columns : Student and Option. Let say there are 50 students. 20 are in Economy option, 20 are in Management option and 10 are in Secretary Option. How can display those numbers. I can display only the 50.
my codes
$qry = "select * from table group by option";
$req= #mysqli_query($conn, $qry);
$result = mysqli_query( $conn, "select id from table");
$num_rows = mysqli_num_rows($result);
Students Total (<?php echo $num_rows ?>)
<table >
<tr>
<th>Student</th>
<th>Option</th>
</tr>
<?php
while($row=mysqli_fetch_array($req))
{
?>
<tr>
<td><?php echo $row['student'] ?></td>
<td><?php echo $row['option'] ?></td>
</tr>
<?php
}
?>
</table>
Here is the query you need:
SELECT COUNT(*) AS `option_count`, * -- returns a count aliased as "options_count"
FROM `table`
GROUP BY `option` -- will group the options and show the counts
Now you can echo the count, along with other data:
echo $row['count_options'];
echo $['options'];
The problem that you have here is that you will not be able to display each student in the option because this counts / groups only the three options.
Behold the proper query :
$qry = "select option as opt, COUNT(*) AS option from table group by option";
I'm new to PHP and I'm trying to figure out how I can compare two mysql query results and echo out the differences. Basically I have a database that is comparing state flag characteristics. The user would select 2 states and what I would like is to have the php echo out 3 sets of results (state 1 only, shared characterisics, and state 2 only). My rough code below only echos out characteristics for states 1 and 2. Is there a way that I can compare the query results, so that I get differences between the states, and also shared characteristics.
<?php $query1 = $_GET['query1'];
$query2 = $_GET['query2'];
$min_length = 2;?>
<!-- state 1 characteristics only -->
<div class="fluid s1charc">
<?php echo "<strong><p>Search results for $query1</strong></p>";?>
<?php if(strlen($query1) >= $min_length){$query1 = htmlspecialchars($query1);
$query1 = mysql_real_escape_string($query1);
$raw_results1 = mysql_query("SELECT * FROM charc_s WHERE `charc_f` ='$query1' ORDER BY FLAG_S") or die(mysql_error());
if(mysql_num_rows($raw_results1) > 0) {
while($results1 = mysql_fetch_array($raw_results1)){
echo "<table id='iseqchart' class='sortable'>
<tr valign='middle'>
<td ><a href='flag.php?FLAG_ID=".$results1['FLAG_ID']."'><img src='images/".$results1['IMAGE']."'></a></td>
<td> </td>
<td><strong><font size='3'><a href='flag.php?FLAG_ID=".$results1['FLAG_ID']."' style='color:#100783'>".$results1['FLAG_S']." (".$results1['STATE'].")</strong></a>
</td>
</tr>
</table>";
}
}
else{ // if there is no matching rows do following
echo "No results were found";
}
}
else{ // if query length is less than minimum
echo " ".$min_length;
}
?>
</div>
<!-- shared characteristics -->
<div class="fluid sharecharc">Shared</div>
<!-- state 2 characteristics only -->
<div class="fluid s2charc">
<?php echo "<strong><p>Search results for $query2</strong></p>"; ?>
<?php if(strlen($query2) >= $min_length){$query2 = htmlspecialchars($query2);
$query2 = mysql_real_escape_string($query2);
$raw_results = mysql_query("SELECT * FROM charc_s WHERE `charc_f` ='$query2' ORDER BY FLAG_S") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0) {
while($results = mysql_fetch_array($raw_results)){
echo "<table id='iseqchart' class='sortable'>
<tr valign='middle'>
<td ><a href='flag.php?FLAG_ID=".$results['FLAG_ID']."'><img src='images/".$results['IMAGE']."'></a></td>
<td> </td>
<td><strong><font size='3'><a href='flag.php?FLAG_ID=".$results['FLAG_ID']."' style='color:#100783'>".$results['FLAG_S']." (".$results['STATE'].")</strong></a>
</td>
</tr>
</table>";
}
}
else{ // if there is no matching rows do following
echo "No results were found";
}
}
else{ // if query length is less than minimum
echo " ".$min_length;
}
?>
</div>
The best way to do this is on the server side. Make the database do 3 different selects. The reason is that the server will run the queries a lot faster than the php. And it will end up in a better user experience.
Only Table A
SELECT * FROM TableA A LEFT JOIN TableB B ON A.key = B.key
Only Table B
SELECT * FROM TableA A RIGHT JOIN TableB B ON A.key = B.key
And in Both Tables
SELECT * FROM TableA A INNER JOIN TableB B ON A.key = B.key
From there echo out your results.
I have one MySQL table and it has two columns -
I want to display in my site like this -
I can easily take the table name Boy | Girl . But when i try to display the table I get like this -
I am just showing one example here. There may be 50 boys and 10 girls.. So I need help.
After displaying the heading
while($row_type = mysql_fetch_array($type))
{
$type_name = $row_type['type_name']; //Boy (or) Girl taking from another table
$type_name = Database::getInstance()->query("SELECT * FROM details WHERE type='type_name'");
echo "<tr>";
while($row_name = mysql_fetch_array($type_name))
{
echo "<td>$row_name[type_name]</td>"; //Displaying the names
}
echo "</tr>";
}
So many views but not getting any answer. Please help guys. Please catch my mistake.
Try with two queries.
Make an array for each category(Male & Female)
It Works.
$maleQuery = mysql_query("SELECT * FROM table WHERE category='male'");
$femaleQuery = mysql_query("SELECT * FROM table WHERE category='female'");
while(($row = mysql_fetch_assoc($maleQuery))) {
$males[] = $row['name'];
}
while(($row = mysql_fetch_assoc($femaleQuery))) {
$females[] = $row['name'];
}
$number_of_rows = max(sizeof($males),sizeof($females));
echo "<table border='1'>";
echo "<tr><td>Male</td><td>Female</td></tr>";
for($i=0;$i<$number_of_rows;$i++)
{
echo "<tr><td>".#$males[$i]."</td><td>".#$females[$i]."</td></tr>";
}
Try this query 100% working but set php code.
SELECT IFNULL(c.Boy,'')AS Boy,IFNULL(c.Girl,'')AS Girl FROM
(SELECT x.name,CASE WHEN (x.category = 'boy') THEN x.name END AS Boy,CASE WHEN (x.category = 'girl') THEN x.name END AS Girl FROM (SELECT * FROM tablename) X)c
Is your problem to do with the creation of the table using PHP or is it related to the SQL query itself?
If it is the creation of the table then I suggest you use two tables embedded in a single table like this. That way you can build the first table using one SQL query, then build the second table using a second query, then display the table and girls and boys will appear side by side regardless of how many entries on each side. Your code would look a bit like this:
echo "<table>
<tr>
<td>
<table>
<tr><th>Boy</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Boy'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
<td>
<table>
<tr><th>Girl</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Girl'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
</tr>
</table>";
If you need to cater for more categories, do an initial search to determine the distinct categories, then put the section of code above that creates the inner table in a loop.
eg. in pseudo code:
echo the outer table <table><tr>
SELECT DISTINCT Category FROM details
while row1=get next category
$cat = row1[0];
echo "<td>
<table>
<tr><th>".$cat."</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = '".$cat."'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
echo the </tr></table> to close the outer table
I've try a lot of ways to get this table print as good as it should but I failed.
I know it's simple thing so I hope you help me with it.
Here's my code:
<?php
include('../connect.php');
$id=$_SESSION['login_user'];
$sql = "Select CourseName , Studentname from course p natural join student t";
$rs_result = mysql_query ($sql, $connection);
echo "<center>";
echo "<table>";
echo "<tr> <th>Course Name</th> <th> Students Name</th> </tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $rs_result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['CourseName'] . '</td>';
echo "<td rowspan=''> $row[Studentname] </td> ";
echo "</tr>";
}
echo "</table>";
echo "</center>";
?>
I want to be something like this
Course | Name | Student name |
Math101 | john, Mike |
...
Also, is the JOIN query between the two tables CORRECT or not?
The two tables are:
Course ( Course name - Course id )
Student ( Student name - Course id )
Try this query
$sql ="SELECT cor.CourseName,GROUP_CONCAT(stu.StudentName) AS StudentName
FROM course AS cor
LEFT JOIN student AS stu
ON stu.CourseId = cor.CourseId";
And change the the line in below
echo "<td rowspan=''>" . $row['Studentname'] . "</td> ";
This line:
echo "<td rowspan=''> $row[Studentname] </td> ";
You are accessing the array element improperly. Studentname should have single quotes around it like such:
echo "<td rowspan=''>" . $row['Studentname'] . "</td> ";
Also, in your query, this may work better:
$sql = "SELECT c.CourseName, s.StudentName
FROM course AS c
INNER JOIN student AS s
ON s.CourseId = c.CourseId";
Please use below format
SELECT CourseName , Studentname
FROM course
INNER JOIN student
ON course.id = student.id
Thanks
The problem is with Your rowspan attribute - You need to provide it with the exact number of rows to span through. Anyway, I think it is the collspan attribute You want to use, so e.g.
echo "<td collspan='2'> {$row['Studentname']} </td> ";
which means it will span through 2 columns, thus stundet's name will be both under the Name and Student name columns.
Is this what You were expecting?
Also I highly recommend not to use mysql_ functions but learn how to use mysqli or at least PDO.
I'm under the impression that you wanted to display a comma-separated list of names of all the students that attend each course, for each separate CourseName. In this case, you could change your SQL query to something like this:
SELECT CourseName, GROUP_CONCAT(Studentname SEPARATOR ', ') as names
FROM Course p NATURAL JOIN Student t
GROUP BY CourseName;
Hello please take a look of this answer. Dynamic rowspan while fetching records from database
I think it might be helpfull.