Count of duplicate selection in database - php

I'm trying to create a count for every option in select option, below is the function I made to do so but I realized all it does it count how many users haven't made a selection. I want it to count how many times each option has been selected in database instead, anyone have any advice?
function teamCount($mysqli){
$count = "SELECT count(selection) FROM users GROUP BY selection HAVING count(*) > 1";
$result = $mysqli->query($count);
$rows = mysqli_fetch_row($result);
echo '('.$rows[0].')';
}
below is table mock up:
username selection
..... Buffalo bills
..... Baltimore ravens
I would like the count to go through the selection column and count duplicate entries in database so it appears as such on front end:
Buffalo Bills [1]
Baltimore Ravens [1]

$count = "SELECT selection, count(*) FROM users GROUP BY selection HAVING count(*) > 1";
you can try this one.

Related

SELECT COUNT with Group BY only return value of 2

I have 6 records 3 of which has identical School and I want to get the result of counting how many school there are inside my database but it only returns the value of 2
$tblnum1 = "SELECT COUNT(*) AS ttldata FROM engoralgrade3 WHERE Years = '$yrr' GROUP BY School";
$tblnum = mysqli_query($conn, $tblnum1);
$tblnm = mysqli_fetch_array($tblnum);
echo $tblnm['ttldata'];//input should be 3
This what my data base looked like
I have checked your table, every school do have 2 rows.
maybe u want to count how many distinct school there are, so change the sql to:
select count(distinct School )from engoralgrade3
or u want to distinct the school name, try :
select distinct School from engoralgrade3
You can try this query it will work
$tblnum1 = "SELECT * FROM engoralgrade3 WHERE Years = '$yrr' GROUP BY School";
$tblnum = mysqli_query($conn, $tblnum1);
$tblnm = mysqli_num_rows($tblnum);
echo $tblnm ;
it may be the var $yrr is not identical for all six records in database which cause make returnred value is 2 not 3 .

For each SQL result, another SQL query? in PHP

I need help at getting data from MySQL Database. Right now I have a query that gives me:
Tournament ID
Tournament Name
Tournament Entry fee
Tournament Start and End date
For tournaments I am registered in. Now I want, for each tournament I am registered in, to count how many users are in that tournament, my points in that tournament, etc.
That info is in table called 'ladder'
ladder.id
ladder.points
ladder.userFK
ladder.tournamentFK
Database: http://prntscr.com/99fju1
PHP CODE for displaying tournaments I am registered in:
<?php
include('config.php');
$sql = "SELECT distinct tournaments.idtournament, tournaments.name, tournaments.entryfee, tournaments.start, tournaments.end
from tournaments join ladder
on tournaments.idtournament= ladder.tournamentFK and ladder.userFK=".$_SESSION['userid']."
group by tournaments.idtournament";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$tournament="<li class='registered' data-id=".$row['idtournament']." data-entryfee=".$row['entryfee']." data-prize=".$tournamentPrize."><span class='name'>".$row['name']."</span><span class='entry-fee'>Entry fee: ".$row['entryfee']."€</span><span class='prize-pool'>Prize pool: €</span><span class='date-end'>".$row['start']."-".$row['end']."</span><span class='btns'><button>Standings</button></span></li>";
echo $tournament;
}
}
$conn->close();
?>
Usually you can combine JOIN, COUNT() and GROUP BY in your query.
Some examples:
MySQL joins and COUNT(*) from another table
This would be the query I think.Change column and table name if its not correct. Not tested but I am sure this will give you some idea to make required query
select count(ladder.tournamentId)as userCount,tournaments.name
from
ladder left join tournaments
on ladder.tournamentId = tournaments.id
where ladder.tournamentId in
(
select tournaments.id from
tournaments left join ladder
on ladder.tournamentId = tournaments.id
where ladder.userId='yourId'
) and ladder.userId <> 'yourId'
group by ladder.tournamentId

PHP, SQL - getting fetch where table id = user id and count other table where row is = user id

Thanks for helping, first I will show code:
$dotaz = "Select * from customers JOIN contracts where customers.user_id ='".$_SESSION['user_id']."' and contracts.customer_contract = ".$_SESSION['user_id']." order by COUNT(contracts.customer_contract) DESC limit $limit, $pocetZaznamu ";
I need to get the lists of users (customers table) ordered by count of contracts(contracts table)
I tried to solve this by searching over there, but I can't... if you help me please and explain how it works, thank you! :) $pocetZanamu is Number of records.
I need get users (name, surname etc...) from table customers, ordered by number of contracts in contracts table, where is contract_id, customer_contract (user id)..
This should do it where is the column name you are counting.
$id = $_SESSION['user_id'] ;
$dotaz = "Select COUNT(`customer_contract`) AS CNT, `customer_contract` FROM `contracts` WHERE `user_id`=$id GROUP BY `customer_contract` ORDER BY `CNT` DESC";
Depending on what you are doing you may want to store the results in an array, then process each element in the array separately.
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
$contracts[$row[1]] = $row[0];
}
foreach ($contracts AS $customer_contract => $count){
Process each user id code here
}
Not sure what you are counting. The above counts the customer_contract for a table with multiple records containing the same value in the customer_contract column.
If you just want the total number of records with the same user_id then you'd use:
$dotaz = "Select 1 FROM `contracts` WHERE `user_id`=$id";
$results = $mysqli->query($dotaz);
$count = mysql_num_rows($results);

How can I retrieve MySQL data into a PHP array and then use that array to run another query?

I have a MySQL database in which there is a table that serves as a master list of representative names ids and his/her respective manager, a table that serves as a list of managers, and four additional tables which serve as time intervals in which daily sales data is recorded (calls taken, time taken after each call, revenue, envelopes, pens and other). I am attempting to gather all the statistics for each representative under a single given manager, four times in a day. My thinking is that I should first gather the names and ids under a given manager, and then use that array(?) to run a query through the various tour intervals to gather the sales statistics. What is the best way to do this?
<?php
include 'db_connect.php';
// Get last name of manager
$query = "SELECT * FROM managers WHERE id = '" . $_SESSION['manager_name'] ."';";
$result = $mysqli -> query($query);
$row = $result -> fetch_array(MYSQLI_NUM);
$manager_first = $row[1];
$manager_last = $row[2];
// Get team members
$rep_query = "SELECT * FROM rep_master WHERE leader = '" . $manager_last . "';";
$rep_list = array();
$rep_result = $mysqli -> query($rep_query);
if ($rep_result) {
while ($rep_row = $rep_result -> fetch_row()) {
array_push($rep_list, $rep_row[1] . " " . $rep_row[2]);
}
};
sort($rep_list);
print_r($rep_list);
// Stat query (using my ID as a testing point)
$stat_query = "SELECT id, total_calls, acw, revenue, envelopes, pens, other FROM tour_1 WHERE id='T441241';";
// Get row data
$stat_row = $stat_result -> fetch_array(MYSQLI_NUM);
echo '<br /><br />';
print_r($stat_row);
?>
Use IN and implode:
print_r($rep_list);
// Stat query (using my ID as a testing point)
$stat_query = "SELECT id, total_calls, acw, revenue, envelopes, pens, other
FROM tour_1 WHERE id IN(".implode(",",$rep_list).")";
Assuming your tour tables all have the same structure, you could use UNIONs on the four shift tables and two LEFT JOINs to do this in a single query. I've added a column to show which tour the info came from. Here, it's not clear how you want to group and filter the statistics, so you may get multiple rows with the same leader and rep. You can add GROUP BY modifiers within the combinedtours nested query and WHERE filters or ORDER BY modifiers at the appropriate locations to optimise the query and group, filter and order the records accordingly.
SELECT `managers`.*, CONCAT(`rep_master`.`first_name`, ' ', `rep_master`.`last_name`), combinedtours.* FROM `managers`
RIGHT JOIN
`rep_master` ON `rep_master`.`leader` = `managers`.`last_name`
LEFT JOIN
(SELECT id, 1 as tour, total_calls, acw, revenue, envelopes, pens, other FROM tour_1
UNION
SELECT id, 2 as tour, total_calls, acw, revenue, envelopes, pens, other FROM tour_2
UNION
SELECT id, 3 as tour, total_calls, acw, revenue, envelopes, pens, other FROM tour_3
UNION
SELECT id, 4 as tour, total_calls, acw, revenue, envelopes, pens, other FROM tour_4
) combinedtours
ON combinedtours.`id` = `rep_master`.`rep_id`

search for element in a php array

I've got
a users table named "members"
a rooms table named "rooms"
a table that associates the user id to the ids of the rooms "membersRooms"
I should write a loop that prints a dropdown for each user with all the rooms, but that adds the attribute "selected" to rooms associated with the user
What's wrong with this loop?
$members = mysql_query("SELECT * FROM members ");
$rooms = mysql_query("SELECT * FROM rooms");
while($member = mysql_fetch_array($members)){
echo("<select>");
$roomsOfUser = mysql_query("SELECT roomID FROM membersRooms WHERE userID=".$member["id"]);
$cuArray = mysql_fetch_array($roomsOfUser);
while($room = mysql_fetch_array($rooms)){
if(in_array($room["id"],$cuArray,true))
echo("<option selected='selected'>".$room["roomName"]."</option>");
else
echo("<option>".$class["roomName"]."</option>");
}
echo("</select>");
}
To make this a little easier on you, you could try utilizing left and right joins on your database. This would significantly reduce your server load and still allow you to do the same functionality.
I believe, if I'm reading your database structure right, that you'ld want something along the lines of:
SELECT members.id as memberID, rooms.id as roomID, rooms.roomName, membersRooms.roomID as memberRoom
FROM members
LEFT JOIN membersRooms
ON members.id = membersRooms.userID
RIGHT JOIN rooms
ON membersRooms.roomID = rooms.id
Then in PHP you should be able to just keep track of when your memberID changes, and when it does, start a new select. If I didn't totally bungle that SQL (which I might have) then the resulting rows should look something like:
memberID | roomID | roomName | memberRoom
1 1 foo 1
1 2 bar 1
2 1 foo 1
2 2 bar 1
So on your loop iteration you would use roomID and roomName to build your select, and if RoomID matched memberRoom then you would select that row.
$rooms query while is dead
while runs once time in while
put this $rooms = mysql_query("SELECT * FROM rooms"); query line
in first while
OK, so you need information from 3 tables - members, rooms, and membersRooms. The rows from members and membersRooms line up 1:1, so we can get both of those with 1 query.
This method will minimize the number of queries needed - if you ever see yourself querying the database in a loop, ask yourself if there's a better way.
$member_query = mysql_query("SELECT * FROM members LEFT JOIN membersRooms ON (members.id = membersRooms.userID)");
$room_query = mysql_query("SELECT * FROM rooms");
$rooms = array();
while ($room = mysql_fetch_assoc($room_query))
$rooms[] = $room;
while ($member = mysql_fetch_assoc($member_query)) {
echo '<select>';
foreach($rooms as $room) {
echo "<option value='{$room['roomID']}' ";
if ($member['roomID'] == $room['id'])
echo 'selected="selected"';
echo ">{$room['roomName']}</option>";
}
echo '</select>';
}
It's worth noting that if members:rooms is a 1:many relation, you don't need to use a third table to join them - just add a roomId to members, and you're fine.

Categories