I have a script i'm working on thats automaticly building team pools. There is several clubs and each club can have multiple teams. Multiple teams in one pool from the same club are not allowed. This is where my script goes wrong. It checks if the team is in the same club that the other teams in the same pool (16 pools,4 teams per pool).
It pops the teamid from an array and compares club ID's in DB, if they have same club ID the teamID gets pushed back into the array and repeats untill it finds team in different club.
Somehow it(sometimes?) fails to push the team back into array and i cannot see what i have done wrong. Is this happens once, i end up with a team less, if it happens more then once, the last(or2 last) pools have empty value's wich will cause the while loop to go forever.
This is a code snippet that compares the team and club ID's.
//TeamA
//set dummyteam if needed, else choose from array
if($dummy != 0){
$teamA = "73";
--$dummy;
}
else{
$teamA = array_pop($teams);
}
$teamB = array_pop($teams);
//TeamB
//is TeamB in different club then Team A?
$ABteamisdifferent = 0;
while($ABteamisdifferent == 0){
if(GetClubID($teamA) == GetClubID($teamB)){
$teams[] = $teamB;
shuffle($teams);
$ABteamisdifferent = 0;
$teamB = array_pop($teams);
}
else{
$ABteamisdifferent = 1;
}
}
......
Full code link
Script output
Function Code
I've wasted 3 hours trying to fix this, but i'm probably overlooking something stupid. Still, any help is greatly appreciated.
You're adding the team back into a $team variables instead of $teams. Simply change the following line:
$team[] = $teamB;
to:
$teams[] = $teamB;
Related
I have one set of results with selected player ID's, and another set of results of all playerID's and the price they will pay and I don't know how to combine the two.
I think the easiest way to explain is to show what I have done so far and what I'm trying to figure out.
I have an input form which gives a dropdown menu (event type) and a list of checkboxes for players:
Event type: Match
X = Player1 Junior
_ = Player2 Senior
X = Player3 Senior
Submitting this gets the player ID's which I can access with this:
foreach ($_POST as $key => $value) {
echo $value;
}
I can then using below query, retrieve the prices that each player within the club would pay for the event, based on the event type and the category of the player.
SELECT prices.price, book.id
FROM prices
JOIN book
ON prices.cat = book.pricecat
WHERE eventType = ?('$eventtype') AND clubID = ?('$clubID')
So now I have these two sets of results
One containing the ID's of selected players.
The other containing all of the clubs playerID's and the Price to be paid for each.
How can I compare the two to get the prices for only the players selected?
Very new to PHP & SQL (4 long days of it!). I'm building the app for personal use and to trial it, need it done when hockey season starts in a week, so not had chance to learn properly from the beginning as I'd want to. Solved many problems but now my head hurts so I'll be very grateful for some advice on how I can solve this one!
Put your two sets of results into two arrays, and then loop through them.
$resultA = (firstset, with selected player names only);
$resultB = (secondset, with all the player names [0] and prices [1]);
$resultC = array(); // our final array that we'll build below
foreach ( $resultA as $selected )
{
foreach ( $resultB as $player )
{
if ( $selected == $player[0] )
{
$resultC[] = $player; // the "[]" adds an element to an array
}
}
}
var_dump($resultC); // show us the final array
I've got two tables; one a list of location names, another a list of companies, a field of which stores potentially multiple locations that the company operates in:
id LocationName
1 Aberdeen
2 Dundee
3 Edinburgh
4 Glasgow
idCompany CompanyName Locations
1 CompanyA 1, 2, 3, 4
2 CompanyB 2, 4
3 CompanyC 1
For each company's details page, I want to list the locations in which they operate, displaying the name of each. Eg. for Company B:
Dundee
Glasgow
etc.
Coming from a VB background, I'd just loop through each dataset and compare each to find the matches, but this is in PHP and I can't get it to work:
// Query for specific firm
$sqlCompany= "SELECT * FROM company_details WHERE CompanyID='".$CompanyID."';";
$rstCompany= mysqli_query($conn, $sqlCompany);
$row = mysqli_fetch_assoc($rstCompany);
// Query list of Locations
$sqlLocationNames= "SELECT * FROM Locations ORDER BY LocationName ASC;";
$rstLocationNames= mysqli_query($conn, $sqlLocationNames);
// Explode the field of locations into an array:
$LocationArray = $row["Locations"];
$LocationArray = explode (",", $LocationArray);
for ($i = 0; $i < count($LocationArray); $i++) {
while ($rowLocationNames = mysqli_fetch_assoc($rstLocationNames)) {
if ($LocationArray[$i]==$rowLocationNames["idLocation"]) {
echo $rowLocationNames["LocationName"]."<br />";
}
}
}
Running this for Company A, I'd expect to get the list of four locations from above, but I only get the first location (Aberdeen). I've tried every combination I can think of, to no avail. I need to keep the data structured this way, as I intend having a select multiple for inserting and also editing the data when I can get this working.
Any ideas where I'm going wrong?
Rather than looping the database fetch inside the iteration of the array, which results in there being no data left to read once you come to the second entry in the array (and hence at most one output, as you are seeing), just loop the database fetch and use in_array to determine whether to output the location name:
while ($rowLocationNames = mysqli_fetch_assoc($rstLocationNames)) {
if (in_array($rowLocationNames["idLocation"], $LocationArray)) {
echo $rowLocationNames["LocationName"]."<br />";
}
}
The problem is that your while loop to read the location names from the db is nested within the for loop. After the the first iteration of the for loop, the database pointer is at the end of the recordset, so when you go through the next iteration, there are no records left to read.
Try reading the records in to an array before entering the for loop and then using the while loop to iterate over the newly created array.
Working in Zend framework and using Doctrine.
I have 1 competition, concisting of several matches ( could be from as little as 4 up to as much as 50 ).
These matches usually have the same players in them.
I have the tables:
Competitions
Matches
Matchresults
Users
First step, get all matches belong to competition, this is easy, so no worries there.
Now it gets tricky:
Step two, get all results of said matches, still ok, i can get the data, but presenting this data is the challenging part.
Step three, get the names from the users table, where the users id is equal to the users id given in the matchresults table.
The end result should be a table looking something like this.
Name Match1 match2 match3 total points
firstname + lastname 50 60 61 171
firstname + lastname 52 56 66 174
I can get all the data correctly, but getting it all in the right field is a bit of a problem.
Could anyone point me in the right direction or maybe give me an example?
Cheers,
Mark
EDIT: clarification.
This is for a fishing competition.
Each match has an x amount of fisherman and these get points according to what they catch.
The calender year has been divided into competitions, 2 or 4, can be different each year.
These matches have a begin-date and an end-date and all matches that have been played in between the begin date and end date of a competition, belong to that competition.
Now the user of the app, wants to make an excell export, showing all the results in the manner i've shown above, the more matches, the more columns with points in them.
You want to make yourself a function which transforms a competition into a list of users along with their results. Something like:
public function transform($competition)
{
$users = array();
$matches = $competition->getMatches();
$matchCount = count($matches);
$matchNum = 0;
foreach($matches as $match)
{
$matchNum++;
foreach($match->getResults() as $result)
{
$user = $result->getUser();
$userId = $user->getId();
// Add new user if necessary
if (!isset($users[$userId]))
{
// Store the name
$users[$userId]['name'] = $user->getFirstName() . ' ' . $user->getLastName();
// Spot to store total points
$users[$userId]['total'] = null;
// Individual match results
$users[$userId]['matches'] = array();
// Spots for each match in case users skip a match
for($i = 1; $i <= $matchCount; $i++) $users[$userId]['matches']['Match' . $i] = null;
}
$points = $result->getPoints();
$users[$userId]['matches']['Match' . $matchNum] = $points;
$users[$userId]['total'] += $points;
}
}
// Use usort if you want to sort by names
// Done
var_dump($users);
return $users;
}
Ive been battling away with the following problem
Ive got a page where I pull names from players specific to their positions in a sport squad.
Example: I will display all the Wings in the squad using a dropdown where a coach can then pick his wing for the game.
There are dropdowns for each different position
The aim of the page is to let the coach quickly select his team for a fixture
After the coach selected his team he will, select the opponents for which the selected team will play against.
When he clicks submit the selected oppents and players will get stored in two arrays which will get called to display the team selected and their opponents on a new page. (After which it will get uploaded to the DB.)
I am having trouble getting the values from the select list to display on the new page.
I guess I have to do something like this on the new page:
foreach ($_REQUEST['opponents'] as $opponents){
print $opponents;
echo'<br>';
}
but it is not giving the desired results.
Strangely what gets printed is the variable name from the previous page select menu.
Upon further inspection I did a vardump on the new page and it says that $opponenets gets passed a value of string which is the variable name and not the value thereof?
My page looks like this
My question is how would I go abouts getting the values from the select dropdowns
if(isset($_POST["submit"]))
{
foreach ($_REQUEST['opponents'] as $against){
var_dump($against);
print $against;
echo'<br>';
}
}
else
{
echo'<h1>Select your Team</h1>';
$x = array("THP", "HKR", "LHP", "LH", "FLH"); //players positions gets assigned to x which will be used to query the database
echo '<form name="playerselect" method="post" action="">';
//query database with different query after each loop
for ($i = 0; sizeof($x) > $i; $i++)
{
//query where position field equeals variable x
$result = mysql_query("SELECT `name`, `position` FROM `player_info`
WHERE `position` = '$x[$i]'") or die(mysql_error()) ;
//Gets data from DB and assigns values to arrays below
while($row = mysql_fetch_array($result))
{
$playername[] = $row['name'];
$position[] = $row['position'];
}
//print player position
print $position[0];
echo'<br>';
//unset the array so that it is empty for the next query in the new loop
unset($position);
echo '<select name="players[]" >' ;
foreach ($playername as $name )
{
//Put playernames relevant to the position in the option element
echo'<option value="$name" selected="selected">'.$name;'</option>';
echo'<br>';
}
echo'</select>';
//unset array so that its contents is empty for the next query in the new loop
unset($playername);
echo'<br>';
}
You cannot. Your submit will only transmit select values. This is not a bug, it is a feature. You do not want to send data back and forth from/to the server/client which is known to both of them.
On the server you are free to query your database at any time. You can also cache your select list into the $_SESSION variable in your initial list read. However this is advanced fittling as your cache list may become outdated and also your server memory utilization must leave space for file caching (the SESSION cache goes to files).
If you go for the database query you may need some ID as sort of anchor. Just put the into the $_SESSION variable - eg.:
$_SESSION['positions']=$x;
In your example the $x seems to be static, which obviously reduces the need to cache it into the $_SESSION - however on other occasions you may need this method.
I checked throught the existing topics. I have a fix for my problem but I know its not the right fix and I'm more interested making this work right, than creating a workaround it.
I have a project where I have 3 tables, diagnosis, visits, and treatments. People come in for a visit, they get a treatment, and the treatment is for a diagnosis.
For displaying this information on the page, I want to show the patient's diagnosis, then show the time they came in for a visit, that visit info can then be clicked on to show treatment info.
To do this a made this function in php:
<?
function returnTandV($dxid){
include("db.info.php");
$query = sprintf("SELECT treatments.*,visits.* FROM treatments LEFT JOIN visits ON
treatments.tid = visits.tid WHERE treatments.dxid = '%s' ORDER BY visits.dos DESC",
mysql_real_escape_string($dxid));
$result = mysql_query($query) or die("Failed because: ".mysql_error());
$num = mysql_num_rows($result);
for($i = 0; $i <= $num; ++$i) {
$v[$i] = mysql_fetch_array($result MYSQL_ASSOC);
++$i;
}
return $v;
}
?>
The function works and will display what I want which is all of the rows from both treatments and visits as 1 large assoc. array the problem is it always returns 1 less row than is actually in the database and I'm not sure why. There are 3 rows total, but msql_num_rows() will only show it as 2. My work around has been to just add 1 ($num = mysql_num_rows($result)+1;) but I would rather just have it be correct.
This section looks suspicious to me:
for($i = 0; $i <= $num; ++$i) {
$v[$i] = mysql_fetch_array($result MYSQL_ASSOC);
++$i;
}
You're incrementing i twice
You're going to $i <= $num when you most likely want $i < $num
This combination may be why you're getting unexpected results. Basically, you have three rows, but you're only asking for rows 0 and 2 (skipping row 1).
Programmers always count from 0. So, you are starting your loop at 0. If you end at 2, you have reached 3 rows.
Row0, Row1, Row2.
if $i = 0, and u increment it BEFORE adding something to the array, u skip the first row. increment $i AFTER the loop runs to start at 0 (first key).
For loops are not good for this: rather do:
$query=mysql_query(' --mysql --- ');
while ($row=mysql_fetch_array($query)){
$v[]=$row["dbcolumn"];
}
return $v for your function then.compact and neat. you can create an associative array, as long as the key name is unique (like primary ids).. $v["$priid"]=$row[1];