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.
Related
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.
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!
This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )
// first query to get cats from user table
$query = "select * from user where name='".$_SESSION['username']."' order by id ASC limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){
$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];
}
}
// now i want to build 10 select boxes with selected according the user table $cats
// below is what i can build to first box $cat1
// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code
<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {
if ( $cat1 == $row['id'] ) {
print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
else {
print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
}
?>
</select>
I am not a coder so this might not be effective code.
Hope someone can help me here and understands what i am trying to do.
Many Thanks.
The code is fine. This 10 cycles as you name it is a almost zero cost.
This is the usual way we do it, we fetch sequentialy the records one by one.
In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.
On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.
for($i=0;$i<99999;$i++)
(9999*9999);
echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
?>
I'm trying to create a dynamic list (5 row results) in php by first getting data from one table then using a resulting var to get the latest uploaded "image_links" (just 1 from each of the 5 artists) from another table -- then echo out.
The code here gives me the only one row with the latest image. When I comment out the "// get the latest image link uploaded ///" section of the code I get the 5 rows of different artists I really want but, of course, w/o images. I tried (among a bunch of things) mysql_result() w/o the while statement but that didn't work.
So what am I missing?
Thanks
Allen
//// first get the artists followed ////////////////
$QUERY= "SELECT * FROM followArtist WHERE user_id = $user_id ";
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_name = $row['artist_name'];
$artist_id = $row['artist_id'];
$date_lastSent = $row['date_lastSent'];
$date_artPosted = $row['date_artPosted'];
$date_notePosted = $row['date_notePosted'];
//// get new notice data /////
if ($date_artPosted >= $date_lastSent) {
$artp = "new artwork posted";
}else{
$artp = "";
}
if ($date_notePosted >= $date_lastSent) {
$notep = "news/announcement posted";
}else{
$notep = "";
}
if ($artp!="" && $notep!="") {
$and = " and<br />";
}else{
$and = "";
}
if ($artp=="" && $notep=="") {
$no = "No new images or news posted since your<br /> last visit, but we'll let you know when there is.";
}else{
$no = "";
}
//////// get the latest image link uploaded ////////////////////////////////////
$QUERY2="SELECT image_link FROM artWork WHERE artist_id ='$artist_id' AND make_avail = '1' ";
//ORDER BY date_submit DESC
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 ){
while($row = mysql_fetch_assoc($res)){
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
//////// end of get the latest images uploaded ////////////////////////////////
echo "<tr align=\"center\" height=\"115px\">
<td align=\"left\" width=\"15%\"> <a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\">
<img src=slir/w115-h115/$path$image_link /></a></td>
<td align=\"center\" width=\"80%\"
<span class=\"deviceMedLtGrayFont\">$artist_name</span>
<br /><br />
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$artp</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$and$no</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$notep</a>
</td>
</tr>";
} //// end bracket for getting latest image link
} ///loop end for getting followed artist data
} ///end: if ($num>0) clause<code>
If I read your code correctly, I see you looping using data from query1 in the control structure, and a lookup on query2 within each loop. You are reusing the variables in your loop1 control structure for query2 ($num and the query handle ($res)) for the second loop. Probably not desirable within the loop.
You're sharing the variables $num and $res between the two queries ... your original properties will be overwritten when the second query is run. Use different property names for the inner query.
Example of problem:
$result = QueryA();
while( $row = $result->getRow() )
{
// -- You're overwriting the original result here ...
$result = QueryB();
// Next time the loop runs, it will run using the result from QueryB();
}
So change ...
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 )
{
while($row = mysql_fetch_assoc($res))
{
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
to
$res2 = mysql_query($QUERY2);
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
while($row2 = mysql_fetch_assoc($res2))
{
$image_link= $row2['image_link'];
}
this is a mess - as others have said you're using the same variables for different purposes.
That you're storing integers which seem to represent enumerations in a char field is bad.
You're iterating through the second result set to find the last record (from an unsorted result set!).
You only need one query - not 2.
SELECT f.artist_name, f.artist_id, f.dateLastSent....
SUBSTR(
MAX(
CONCAT(DATE_FORMAT(date_submit, '%Y%m%d%H%i%s'), a.image_link)
), 15) as img_link
FROM followArtist f
LEFT JOIN artWork a
ON (a.artist_id=f.artist_id AND a.make_avail = '1')
WHERE user_id = $user_id
GROUP BY f.artist_name, f.artist_id, f.dateLastSent....
I will try to be as clear as possible because I can't get anybody to help me around,
I am trying to associate some data from a 'videos' table with their respective ID.
Lets say, I have column ID, title, serie, season, episode.
I am getting my data :
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
?>
(that is in the page where you see the video itself)
So now I can get the number of episodes from a serie and season.
What I'm trying to do is have a link for the next episode, and aa link for the previous one. In the URL I am working with the id, so http://website.com/view/id/'video id here'/
So how can I get the ID of the following and previous episodes of the same season AND serie?
Help will be much appreciated!
The easiest thing I thought of is
<?=$row['id'] + 1?>
<?=$row['id'] - 1?>
But the thing is that it's mixed videos, so it wont work 100%
I think you've taken my example too literally. I'll post a complete example in the morning (I'm just replying from my iPhone at the mo). For some reason it wouldn't let me add a comment to your last reply, so sorry this is as an answer.
[edit] here's a more complete example:
<?php
$result = mysql_query("SELECT * FROM videos WHERE series='$series' AND season = '$season'");
$last_row = null;
$next_row = null;
$current_id = $_GET['id'];
while($row = mysql_fetch_assoc($result)) {
if($current_id == $row['id']) {
$next_row = mysql_fetch_assoc($result);
break;
}
$last_row = $row;
}
if($last_row != null) {
echo "<a href='?id={$last_row['id']}'>Prev</><br/>\n";
}
if($next_row != null) {
echo "<a href='?id={$next_row['id']}'>Next</><br/>\n";
}
?>
A few things to note:
This is untested.
In your initial example, I didn't know where you were getting the $row['serie'] and $row['season'], so in my example, I've just used the variables $series and $season. You'll have to fill these in with what you want the current result set to be filtered by.
For my example, the URL format uses the GET layout (ie. ?id=).
If you do:
$results = mysql_query($sql);
(where $sql is your mentioned select statement)
Then the $results array will contain all results of that series/season.
So you can access it via:
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
Note that you'll of course need to check that $n - 1 isn't less than zero, and ($n + 1) isn't greater than your $total_rows.
Here is what I tried, I guess it is what you meant,
All that it's doing is put the previous episode, so I get /view/id/3/ (if the episode i am watching is 4)
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
?>
<? if($row['episode'] == 1) { ?>
<td align="center" width="33%"></td>
<? } else { ?>
<td align="center" width="33%"><img src="images/previous.gif" srcover="images/previoush.gif" alt="Previous Video" border="0" /></td><? } ?>
That is only for the previous one,
Sorry I had to post like this, if not it wouldnt have appeared correctly,
(Correct me if I'm wrong with the code)
And thanks for the reply