Joomla session variables and retrieving wrong values - php

I'm doing some custom coding for a Joomla installation that uses jReviews.
In a module on my home page I pass an array of content id's to a session variable (step 1) and then in other pages such as Top Products or Special Offers I might send a different set of values to the same session variable (step 2), each time the values are related to certain attributes, something like a 'related products' function. When finally I view a product, I should get the values sent in step 2 but instead, I'm getting the values from step 1.
This is what I'm doing:
Step 1:
$db =& JFactory::getDBO();
$query = "select * from jos_jreviews_content jrc
join jos_content jc on jrc.contentid = jc.id
where jc.state=1 and jc.catid=10 order by jc.id desc limit 100";
//state 1= published, catid 10= products,
$db->setQuery($query);
$allproducts = $db->loadObjectList();
$nav_session = JFactory::getSession();
$nav_listings_ids = array();
if(count($allproducts)) {
$i=0;
foreach($allproducts as $relatedproduct) {
$listingid = $relatedproduct->id;
$alias = $relatedproduct->alias;
$nav_listings_ids[$i]["id"] = $relatedproduct->contentid;
$nav_listings_ids[$i]["link"] = "index.php?option=com_content&view=article&catid=10:products&id=".$listingid.":".$alias."&Itemid=16";
$nav_listings_ids[$i]["title"] = $relatedproduct->title;
$i++;
}
}
// Save to session var
$nav_session->set('related_results_listings', $nav_listings_ids);
Step 2:
$jrcompanyname = '*'.$listing['Field']['pairs']['jr_companyname']['value'][0].'*';
$db =& JFactory::getDBO();
$query = "select * from jos_jreviews_content jrc
join jos_content jc on jrc.contentid = jc.id
where jrc.jr_companyname = '".$jrcompanyname."' and jc.state=1 and jc.catid=10 order by jrc.contentid desc";
$db->setQuery($query);
$relatedproducts = $db->loadObjectList();
$nav_session = JFactory::getSession();
$nav_listings_ids = array();
if(count($relatedproducts)) {
$i=0;
foreach($relatedproducts as $relatedproduct) {
$listingid = $relatedproduct->id;
$alias = $relatedproduct->alias;
$nav_listings_ids[$i]["id"] = $relatedproduct->contentid;
$nav_listings_ids[$i]["link"] = "index.php?option=com_content&view=article&catid=10:products&id=".$listingid.":".$alias."&Itemid=16";
$nav_listings_ids[$i]["title"] = $relatedproduct->title;
$i++;
}
}
// Save session
$nav_session->set('related_results_listings', $nav_listings_ids);
On my product page I loop through the values of $_SESSION['related_results_listings'] to find the position of the item I'm viewing:
$nav_session = JFactory::getSession();
$nav_listings = $nav_session->get("related_results_listings");
// Locate the current listing in the search results list and retrieve the previous and next items
$index = 0;
for( $i=0; $i<count($nav_listings); $i++ )
{
if( $nav_listings[$i]["id"] == $listing['Listing']['listing_id'] )
{
$index = $i;
break;
}
}
I'll be glad to explain any of the above if someone is willing to help me out. Thanks in advance and Happy New Year to all!

Related

Issue in displaying selecting data

My issue is to display the data. It repeats the same id in it several times.
<?php
$check_shared_section = mysqli_query($MYSQLi,"select * from `vp_wall_post` where `type` = 'section' and `username` = '".mysqli_real_escape_string($MYSQLi,$poster_username)."' ");
$get_section = mysqli_fetch_array($check_shared_section);
$section_post = trim(strip_tags($get_section["post"]));
$section_page = trim(strip_tags($get_section["page_id"]));
$section_id = trim(strip_tags($get_section["pid"]));
echo $section_id;
?>
These are the issues that I am facing. Please help me to solve this problem.
It shows the output id
e4zDFOL3jBgcH8YRfkzJ
e4zDFOL3jBgcH8YRfkzJ
e4zDFOL3jBgcH8YRfkzJ
I want to show different id
e4zDFOL3jBgcH8YRfkzJ
er556gdfg4asffgfgfgg
So2cLYtCTTMYD0fCNFjq
JGH63vAqIAnt5jNCH6OL
<?php
$check_shared_section = mysqli_query($MYSQLi,"select * from `vp_wall_post` where `type` = 'section' and `username` = '".mysqli_real_escape_string($MYSQLi,$poster_username)."' ");
$get_section = mysqli_fetch_array($check_shared_section);
$section_post = trim(strip_tags($get_section["post"]));
$section_page = trim(strip_tags($get_section["page_id"]));
$section_id = trim(strip_tags($get_section["pid"]));
echo $section_id;
?>
I'm not sure why you are seeing the same pid value multiple times as you don't have any looping in your code at all. However the reason you are not getting all the different pid values is that you're not looping the results of the query. You need to use a while loop on the result of mysqli_fetch_array e.g.
while ($get_section = mysqli_fetch_array($check_shared_section)) {
$section_post = trim(strip_tags($get_section["post"]));
$section_page = trim(strip_tags($get_section["page_id"]));
$section_id = trim(strip_tags($get_section["pid"]));
echo $section_id;
// do other stuff with the values
}
Note that if you want to further process the results outside the while loop, you will need to save the values into arrays e.g.
$section_posts = array();
$section_pages = array();
$section_ids = array();
while ($get_section = mysqli_fetch_array($check_shared_section)) {
$section_posts[] = $section_post = trim(strip_tags($get_section["post"]));
$section_pages[] = $section_page = trim(strip_tags($get_section["page_id"]));
$section_ids[] = $section_id = trim(strip_tags($get_section["pid"]));
echo $section_id;
// do other stuff with the values
}
// you can use other loops to further process the values here
// e.g. foreach ($section_posts as $index => $section_post) {
// you can use $index to access the corresponding values from
// the $section_pages and $section_ids arrays e.g.
// $section_page = $section_pages[$index]

Array and for each loop issues

Code is below if I run one value in the array the results are correct if I run more than one value the results are of the price is incorrect its like it has messed around with the values somewhere ?? help appreciated
$dido=array('42204131','22204131');
foreach($dido as $did):
$query = "select * from dispatch,link where lid=dlid and did=$did";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$vanc1=$row['vanc1'];
$vanc2=$row['vanc2'];
$vanc3=$row['vanc3'];
$vanc4=$row['vanc4'];
$vanc5=$row['vanc5'];
$anc1=$row['anc1'];
$anc2=$row['anc2'];
$anc3=$row['anc3'];
$anc4=$row['anc4'];
$anc5=$row['anc5'];
// price anc1
$querypanc1 = "select pprice from products where pid=$anc1";
$resultpanc1 = mysql_query($querypanc1);
while($row = mysql_fetch_array($resultpanc1))
{
$priceanc1=$row[pprice];
$tpriceanc1=$vanc1*$priceanc1;
}
// price anc2
$querypanc2 = "select pprice from products where pid=$anc2";
$resultpanc2 = mysql_query($querypanc2);
while($row = mysql_fetch_array($resultpanc2))
{
$priceanc2=$row[pprice];
$tpriceanc2=$vanc2*$priceanc2;
}
// price anc3
$querypanc3 = "select pprice from products where pid=$anc3";
$resultpanc3 = mysql_query($querypanc3);
while($row = mysql_fetch_array($resultpanc3))
{
$priceanc3=$row[pprice];
$tpriceanc3=$vanc3*$priceanc3;
}
// price anc4
$querypanc4 = "select pprice from products where pid=$anc4";
$resultpanc4 = mysql_query($querypanc4);
while($row = mysql_fetch_array($resultpanc4))
{
$priceanc4=$row[pprice];
$tpriceanc4=$vanc4*$priceanc4;
}
// price anc5
$querypanc5 = "select pprice from products where pid=$anc5";
$resultpanc5 = mysql_query($querypanc5);
while($row = mysql_fetch_array($resultpanc5))
{
$priceanc5=$row[pprice];
$tpriceanc5=$vanc5*$priceanc5;
}
$gtprice=$tpriceanc1+$tpriceanc2+$tpriceanc3+$tpriceanc4+$tpriceanc5;
$qrygt="UPDATE dispatch SET gtprice=$gtprice WHERE did=$did";
$resultgt=#mysql_query($qrygt);
}
endforeach;
1) The only possible issue I could spot in your code, is that when some of your select pprice from products where pid ... queries do not return any data, you retain value of $tpriceancX from previous iteration.
2) Also (out of topic) you can replace your 5 blocks of repeated code with for loop.
$gtprice = 0;
for ($i = 1; $i <= 5; $i++)
{
$querypanc = "select pprice from products where pid=".$row["anc$i"];
$resultpanc = mysql_query($querypanc);
while($pancrow = mysql_fetch_array($resultpanc))
{
$priceanc=$pancrow[pprice];
$tpriceanc=$row["vanc$i"]*$priceanc;
$gtprice += $tpriceanc;
}
}
Your first and biggest problem is the copy-pasta nature of your code. Let's try and break down what you're doing:
Setting up a list of ids
Running a query on those ids
Putting the results into an array
Running a separate query on each of those results
You are also using some very janky syntax. (ie foreach($foo as $bar):).
Break these things down into methods. What is a method? It takes an input and transforms it into an output.
//returns an array of price information
public function getPrices($idArray) { //note the good method and parameter names!
//do stuff
}
Now that we know what we are doing, we can start to fill in the implementation details:
public function getPrices($idArray) {
foreach($idArray as $id) {
//somehow get the gross-scale information
//then put it in a data object
//then call a function to get specific information
}
}
What should that sub-method do? Lets look at your current code snippet:
// price anc1
$querypanc1 = "select pprice from products where pid=$anc1";//sets up sql query
$resultpanc1 = mysql_query($querypanc1); //runs the query
while($row = mysql_fetch_array($resultpanc1)) { //for each result
$priceanc1=$row[pprice]; //gets the price
$tpriceanc1=$vanc1*$priceanc1; //calculates some other price
}
Those last two lines really suggest an object but maybe that's too heavyweight for your purpose. The first two lines are boiler plate you repeat endlessly. Lets write a function!
public function getPrices($name, $pid, $multiplier) {
$sqlQuery = "SELECT pprice FROM products WHERE pid=$pid";
$result = mysql_query($sqlQuery);
$prices = array();
while ($row = mysql_fetch_array($result) {
$key = "price".$name;//$key will be something like 'priceanc1'
$prices[$key] = $row[pprice];
$tkey = "tprice".$name;
$prices[$tkey] = $prices[$key] * $multiplier;
}
}
Now, this function is a bit unclean because it tries to do two things at once (queries the database and then massages the data into a usable array) but I wanted it to resemble what you were doing. With this function written we can go back to our higher level function an call it:
public function getPrices($idArray) {
foreach($idArray as $id) {
$sqlQuery = "SELECT * from dispatch, link WHERE lid=dlid and did=$id";
$prices = array();
while ($row = mysql_fetch_array($result) {
for ($idx = 1; $idx <= 5; $idx++) {
$name = "anc".$idx;
$pid = $row[$name];
$multiplier = $row["vanc".$idx];
$priceArray = getPrices($name, $pid, $multiplier);
$prices = array_merge($prices, $priceArray);
}
}
}
//put a var_dump here to check to see if you're getting good results!
return $prices;//Should be the aggregated prices you've gotten from the db
}
Now, that is what you're attempting to do, but I admit I don't understand how your database is set up or what your variables actually mean. Pressing on! We also note that unnecessary massaging of data falls away.
You can call this like so:
$ids = array();
$ids[] = 42204131;
$ids[] = 22204131;
$prices = getPrices($ids);
var_dump($prices);//shows the result of your work
Now that you have the prices, you can pass them to another function to run the update:
updatePrices($prices);
I'll let you write that part on your own. But remember; break down what you're doing and have repeated elements be handled by the same function. The real lesson to learn here is that programming is really communicating: your code doesn't communicate anything because there is so much repeated noise. Use good variable names. Tighten what you're doing down to functions with single tasks. This way anyone reading your code (including you!) will know what you're trying to do and where you've gone wrong.

MySQL sorting with PHP

I'm trying to accomplish the following situation:
$mysql_query = "
SELECT *
FROM st_users
WHERE
`user_comp_supervisor_id` = '$team_supervisor' AND
`user_exempt_from_goals` = '0'
ORDER BY 'calculate_progress_percent()' ASC
";
I know that I can't accomplish ordering by a function in a MySQL statement, but I'm trying to figure out how to take all the returned records, and then order them in order of highest to lowest from a php function result. Any ideas would be greatly appreciated; I've been trying to wrap my head around this for a few hours now... :-(
function diy_calc_progress_percent($user_id,$period_id,$period_week_number)
{
$this->user_id = $user_id;
$this->period_id = $period_id;
$this->period_week_number = $period_week_number;
if ($this->period_week_number == 1)
{
$this->week_id = mysql_result( mysql_query(" SELECT `period_week_one` FROM `st_comp_periods` WHERE `period_id` = '$this->period_id' "),0 );
}
else if ($this->period_week_number == 2)
{
$this->week_id = mysql_result( mysql_query(" SELECT `period_week_two` FROM `st_comp_periods` WHERE `period_id` = '$this->period_id' "),0 );
}
else
{
echo "Week number not valid.";
exit();
}
$this->week_start_date = mysql_result( mysql_query(" SELECT `week_start_date` FROM `st_comp_weeks` WHERE `week_id` = '$this->week_id' "),0 );
$this->week_end_date = mysql_result( mysql_query(" SELECT `week_end_date` FROM `st_comp_weeks` WHERE `week_id` = '$this->week_id' "),0 );
$this->user_department = $this->user_info($this->user_id,"user_comp_department_id");
$this->user_week_diy_goal = mysql_result( mysql_query(" SELECT `goal_diy_department` FROM `st_comp_department_goals` WHERE `goal_department_id` = '$this->user_department' AND `goal_week_id` = '$this->week_id' "),0 );
$this->calc_totals_result = mysql_query("SELECT SUM(record_total_diy_revenue) AS user_week_total FROM `st_entered_records` WHERE `record_user_id` = '$this->user_id' AND `record_date` BETWEEN '$this->week_start_date' AND '$this->week_end_date'");
$this->calc_totals_row = mysql_fetch_assoc($this->calc_totals_result);
$this->user_week_total = $this->calc_totals_row['user_week_total'];
$this->user_week_one_percent = ($this->user_week_total / $this->user_week_diy_goal) * 100;
$this->user_week_one_percent = number_format( (float)$this->user_week_one_percent, 2, '.', '' );
return $this->user_week_one_percent;
}
You probably will have to do some array juggling.
First get all your entries FROM st_users into a first array (mysql_query)
Then you could run through that array, and for each entry you do the calculate_progress_percent() and build up a second array in which you could add the additional info ("user_progress_percent").
After this you can sort the new array ba your new info ("user_progress_percent").
And here is some quick and dirty code-suggestions – code is however not tested… of course…:)
First:
$mysql_query = "SELECT * FROM st_users
WHERE `user_comp_supervisor_id`='$team_supervisor' AND
`user_exempt_from_goals` = '0'";
Then something like this:
$i = 0;
while($tmp = mysql_fetch_array($mysql_query)) {
$my_second_array[$i]['user_id'] = $tmp['user_id'];
$user_id = $my_second_array[$i]['user_id'];
diy_calc_progress_percent($user_id,$period_id,$period_week_number);
$my_second_array[$i]['user_result'] = $diy_calc_progress_percent_result;
$i++;
}
And then sorting that second array should be possible as described here:
Sort Multi-dimensional Array by Value
…hope this helps at some point…

Exhausting Memory - Tried Fixing Loops, Still Does Not Work

I'm currently experiencing a memory usage issue - but I cannot figure out where. I've tried replacing some of my foreach loops with for loops or by issuing another query to the DB, but I am still gettting the same error - "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in on line 109". Can anyone provide some insight as to what may be causing the issue? Thank you!
Code after #Patrick 's answer:
$participating_swimmers = array();
$event_standings = array();
$qualifying_times = array();
$events = array();
$current_event = '';
$select_times_sql = "SELECT event, time, name, year, team, time_standard, date_swum
FROM demo_times_table
WHERE sex = 'M' AND (time_standard = 'A' OR time_standard = 'B')
ORDER BY event, time ASC";
$select_times_query = mysql_query($select_times_sql);
//Create array with the current line's swimmer's info
while ($swimmer_info = mysql_fetch_assoc($select_times_query)) {
if($current_event != $swimmer_info['event']){
$events[] = $current_event = $swimmer_info['event'];
}
//Create array with the current line's swimmer's info
$swimmer_info["time"] = $select_times_row['time'];
$swimmer_info["name"] = $select_times_row['name'];
$swimmer_info["year"] = $select_times_row['year'];
$swimmer_info["team"] = $select_times_row['team'];
$swimmer_info["time_standard"] = $select_times_row['time_standard'];
$swimmer_info["date_swum"] = $select_times_row['date_swum'];
//Create "Top 8" list - if more than 8 A cuts, take them all
if (($swimmer_info["time_standard"] == "A") || ($swimmer_info["time_standard"] == "B")) {
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
if ((count($event_standings[$current_event]) < 8) || ($swimmer_info["time_standard"] == "A")) {
//Add swimmer to the list of invites
$event_standings[$current_event][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
} else {
//Add the qualifying time that did not fit into the list to a list of qualifying times
$qualifying_times[$current_event][] = $swimmer_info;
}
}
}
//Sort each array of times in descending order
arsort($event_standings);
arsort($qualifying_times);
$num_of_swimmers = count($participating_swimmers);
while ($num_of_swimmers < 80) {
foreach ($events as $loe) {
$num_of_qualifying_times = count($qualifying_times[$loe]);
$swimmer_info = $qualifying_times[$loe][$num_of_qualifying_times-1];
$event_standings[$loe][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$new_num_of_swimmers = count($participating_swimmers);
if($num_of_swimmers == $new_num_of_swimmers) break;
else $num_of_swimmers = $new_num_of_swimmers;
}
arsort($event_standings);
arsort($qualifying_times);
foreach($event_standings as $loe => $event_swimmer) {
echo "<h1>",$loe,"</h1><br />";
foreach ($event_swimmer as $es) {
echo $es["time"]," ",$es["name"]," ",$es["team"],"<br />";
}
}
Large data in database is the problem 95% !
- try using limit x,y in your queries , and put those queries in some loop .
- see http://php.net/manual/en/function.mysql-free-result.php it might help
<?php
$participating_swimmers = array();
$event_standings = array();
$qualifying_times = array();
$select_times_sql = "SELECT *
FROM demo_times_table
WHERE sex = 'M'
ORDER BY time ASC";
$select_times_query = mysql_query($select_times_sql);
while ($select_times_row = mysql_fetch_assoc($select_times_query)) {
//Create array with the current line's swimmer's info
$swimmer_info["time"] = $select_times_row['time'];
$swimmer_info["name"] = $select_times_row['name'];
$swimmer_info["year"] = $select_times_row['year'];
$swimmer_info["team"] = $select_times_row['team'];
$swimmer_info["time_standard"] = $select_times_row['time_standard'];
$swimmer_info["date_swum"] = $select_times_row['date_swum'];
//Create "Top 8" list - if more than 8 A cuts, take them all
if (($swimmer_info["time_standard"] == "A") || ($swimmer_info["time_standard"] == "B")) {
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
if ((count($event_standings[$current_event]) < 8) || ($swimmer_info["time_standard"] == "A")) {
//Add swimmer to the list of invites
$event_standings[$current_event][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
} else {
//Add the qualifying time that did not fit into the list to a list of qualifying times
$qualifying_times[$current_event][] = $swimmer_info;
}
}
}
mysql_free_result($select_times_query);
//Sort each array of times in descending order
arsort($event_standings);
arsort($qualifying_times);
$num_of_swimmers = count($participating_swimmers);
$sql = "SELECT DISTINCT(event)
FROM demo_times_table
WHERE sex = 'M' limit 80";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$loe = $row['event'];
$num_of_qualifying_times = count($qualifying_times[$loe]);
$event_standings[$loe][] = $qualifying_times[$loe][$num_of_qualifying_times-1];
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $qualifying_times[$loe][$num_of_qualifying_times]["name"];
$condensed_swimmer_info["year"] = $qualifying_times[$loe][$num_of_qualifying_times]["year"];
$condensed_swimmer_info["team"] = $qualifying_times[$loe][$num_of_qualifying_times]["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$num_of_swimmers = count($participating_swimmers);
mysql_free_result($query);
arsort($event_standings);
arsort($qualifying_times);
$sql = "SELECT DISTINCT(event)
FROM demo_times_table
WHERE sex = 'M'";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$loe = $row['event'];
echo "<h1>".$loe."</h1><br />";
foreach ($event_standings[$loe] as $es) {
echo $es["time"]." ".$es["name"]." ".$es["team"]."<br />";
}
}
/*
foreach ($participating_swimmers as $ps) {
echo $ps["name"]."<br /><br />";
}
echo "<br /><br />";
*/
?>
Instead of doing a query within a query, with the potential for logic holes that create a never-ending loop, you can condense it into a single query. For your first block, both loops are just checking for the current event and the sex of the participant, right? So:
$result = SELECT * FROM <my database> WHERE sex = 'M' ORDER BY time ASC
Then you can pull whichever rows you want during the while ($row = mysql_fetch_assoc($result)) loop and compensate for non-distinct values in another way.
One other source of the never-ending loop could be in the block where you sort the qualifying times. You're using "unset" after each, which could be getting the pointer stuck. You could try adding array_values($qualifying_times) after the unset to reindex the array.
Frist off, lose the SELECT DISTINCT like so:
$events = array()
$current_event = '';
$select_times_sql = "SELECT event, time, name, year, team, time_standard, date_swum
FROM demo_times_table
WHERE sex = 'M' AND (time_standard = 'A' OR time_standard = 'B')
ORDER BY event, time ASC";
$select_times_query = mysql_query($select_times_sql);
//Create array with the current line's swimmer's info
while ($swimmer_info = mysql_fetch_assoc($select_times_query)) {
if($current_event != swimmer_info['event']){
$events[] = $current_event = $swimmer_info['event'];
}
//Create "Top 8" list - if more than 8 A cuts, take them all
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
This also loses a bit of redundant code, and can speed up the final output (note the commas in the echo statements - the string doesn't need to be concatenated before it is spat out)
foreach($event_standings as $loe => $event_swimmer) {
echo "<h1>",$loe,"</h1><br />";
foreach ($event_swimmer as $es) {
echo $es["time"]," ",$es["name"]," ",$es["team"],"<br />";
}
}
The final problem lies in the second while loop, where the info being put into $condensed_swimmer_info doesn't have the -1 in place, thus is always blank, and $num_of_swimmers never rises to more than 1 over its original value:
while ($num_of_swimmers < 80) {
foreach ($events as $loe) {
$loe = $row['event'];
$num_of_qualifying_times = count($qualifying_times[$loe]);
$swimmer_info = $qualifying_times[$loe][$num_of_qualifying_times-1];
$event_standings[$loe][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$new_num_of_swimmers = count($participating_swimmers);
if($num_of_swimmers == $new_num_of_swimmers) break;
else $num_of_swimmers = $new_num_of_swimmers;
}

Stumped in the middle of a PHP loop

Here's what I've got so far-
$awards_sql_1 = mysql_query('SELECT * FROM categories WHERE section_id = 1') or die(mysql_error());
$awards_sql_2 = mysql_query('SELECT * FROM categories WHERE section_id = 2') or die(mysql_error());
$awards_sql_3 = mysql_query('SELECT * FROM categories WHERE section_id = 3') or die(mysql_error());
$awards_sql_4 = mysql_query('SELECT * FROM categories WHERE section_id = 4') or die(mysql_error());
$loop = 1;
while($row_sections = mysql_fetch_array($sections_query)) {
$category = 1;
echo "<h3>" . $row_sections['section_name'] . " (Loop# $loop)</h3>";
while($categories = mysql_fetch_array(${"awards_sql_{$loop}"})) {
${"winners_sql_{$loop}"} = mysql_query("SELECT * FROM 2009_RKR_bestof WHERE section = $loop && category = $category ORDER BY result_level ASC") or die(mysql_error());
echo "<h4><strong>{$categories['category_name']}</strong></h4>";
echo "<ul class=\"winners\">";
>> while($winners = mysql_fetch_array(${"winners_sql_{$loop}"})) {
switch ($winners['result_level']) {
case 1: $result_level = "Platinum"; break;
case 2: $result_level = "Gold"; break;
case 3: $result_level = "Silver"; break;
}
if (isset($winners['url'])) { $anchor = ""; $close = ""; }
echo "<li>$anchor{$winners['winner']}$close ($result_level)</li>";
unset($anchor);
unset($close);
}
echo "</ul>";
$category++;
}
$loop++;
}
Where I'm getting stumped, is I'm getting this thing to loop through correctly, my loop counter ($loop) is working, but when it gets time to spit out the actual reward recipients after the first loop through winners, it's only producing the category titles, the list-items are not getting looped out.
I added a little pointer to where I think the problem begins or centers around (>>).
My guess is I need to maybe unset a var somewhere, but I don't know, I can't see it.
I'm with KM - you're displaying a single page and with your loops, you've got a LOT of queries happening at once - what if 1,000 people hit that page at the same time? ouch...
Maybe consider a larger query (with some repeated data) and loop through it once?
For example:
SELECT
section_name,
category_name,
result_level,
url,
winner
FROM 2009_RKR_bestof
INNER JOIN categories ON 2009_RKR_bestof.category = categories.id
INNER JOIN sections ON 2009_RKR_bestof.section = sections.id
ORDER BY section_name,category_name ASC
In your loop, you can do checks to determine if you're in a new section (category/whatever):
//pseudo-code
$current_section = "";
while($stuff = mysql_fetch_array($sql))
{
if ($current_section == "")
{
$current_section = $stuff["section_name"];
}
if ($current_section == $stuff["section_name"])
{
//keep going in your loop
}
else
{
//we've gotten to a new section - so close your html and start a new section
}
}
You get the idea..
My guess would be that it is a data problem. It isn't having trouble reading the titles, only the winners. If it iterated once, I would check the data, and ensure that winners_sql_2 - winnders_sql_4 are getting actual data. Perhaps add an echo winners_sql_2 line, to output the contents of the query, and ensure the query is framed correctly.

Categories