Im learning PHP by working on a personal project. Ive spend the last 2-hours trying to figure out why my IF statment is getting skipped inside my loop, Im a more experienced coder could provide me with a bit of help here, as I am currently at a stalemate.
What Im Trying To do
User makes picks for a round in sports tournament, when round is completed calculate the user standings based on number of correct picks.
Everything works as expected except Im having an (extremely) hard time calculating the number of correct picks.
IMAGE1: THE CODE SHOULD PUT OUT THE FOLLOWING
IMAGE2: THE CODE CURRENTLY PUTS OUT THE FOLLOWING (WRONG)
MY Code
$sql ="SELECT picks.*, results.*, users.*
FROM picks
inner join results on picks.gameID = results.gameID
inner join users on picks.userID = users.userID
WHERE picks.tournament = 'SixNations' AND picks.weekNum = '3'
order by users.lastname, users.firstname";
$stmnt = $db->prepare($sql);
//JUST DISABLING FOR DEBUGING PURPOSES
/*
$stmnt->bindValue(':tournament', $tournament);
$stmnt->bindValue(':weekNum', $round);*/
$stmnt->execute()
$picks = $stmnt->fetchAll();
$totalCorrectPicks = 0;
echo'<table class="table table-responsive table-striped">';
echo'<thead>';
echo'
<tr>
<th>FirstName</th>
<th>Picked Team</th>
<th>Winning Team</th>
<th>Margin</th>
<th>TOTAL CORRECT PICKS</th>
</tr>
</thead>
<tbody>';
$i = 1; //USED TO COUNT NR GAMES
foreach($picks as $pick){
$user = $pick['firstname'];
$picked = $pick['selectedTeam'];
$result = $pick['won'];
$nrGames = $i;
echo '<tr>';
echo'<td>';
echo $user;
echo'</td>';
echo'<td>';
echo $pick['selectedTeam'];
echo'</td>';
echo'<td>';
echo $pick['won'];
echo'</td>';
if($picked == $result){
//USER PICKED CORRECT TEAM
$totalCorrectPicks = $totalCorrectPicks +1;
echo'<td>';
$margin = abs($pick['pts'] - $pick['points']);
echo $margin;
echo'</td>';
}//if
else if($picked != $result){
//user PICKED INCORRECT TEAM
echo'<td>';
$totalCorrectPicks += 0;
$margin = '<span style="color:red">WRONG PICK</span>';
echo $margin;
echo'</td>';
}//else if
##THIS IF STATMENT IS GETTING IGNORED##
if($user != $pick['firstname']){
echo'<td>';
echo $output = 'Total Correct Picks'. $totalCorrectPicks.' / '.$i;
echo'</td>';
echo'</tr>';
}//if
$i++; //keep track of number games
}//foreach
echo'</tbody>';
echo'</table>';
As can be seen on image 2, and the code above the IF statement which should print the total correct games picked by each user is getting skipped / ignored. Any advise / help on why and / how I can fix this very welcome.
Hope this might help:
CODE 1
// Assign Variable
$user = $pick['firstname'];
$nrGame = 1;
// Check user are the same from previous row or not
if($tempUser <> $user){
$points = 0;
$nrGame = 1;
}
// Pick correct team
if ($picked == $result){
$points += 1;
}
// Last Column
echo "<td>".$points." / " .$nrGame."</td>";
// Assign temporary user
$tempUser = $user;
$nrGame++;
CODE 2 (Display Points on the last row only)
// Assign variable
$maxGame = 3;
// Last Column
if ($nrGame == $maxGame)
echo "<td>".$points." / " .$nrGame."</td>";
else
echo "<td></td>";
You have:
foreach($picks as $pick){
$user = $pick['firstname'];
Then later on - in the same foreach you check for this (which you say is the problem):
if($user != $pick['firstname']){
But at no point do you update $user between the first assignment of $user = $pick['firstname']; and the if($user != $pick['firstname']) statement.
This means that the if($user != $pick['firstname']) will always be skipped because you assigned $user = $pick['firstname'] at the start of the loop.
Edit:
In answer to your question - if I understand it correctly. You can simply do something like:
Get the first user name.
// Before the foreach call, need the 'first' user name.
$previousUser = $picks[0]['firstname'];
foreach($picks as $pick){
Check for mis-match:
// For the statement check, where the "problem" is
if($previousUser != $pick['firstname'])
And place this at the end of the loop.
// At the end of the loop
$previousUser = $user;
$i++; //keep track of number games
Related
Can't believe this is giving me a problem but here it is. An example of the query and code is:
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
/* I want to echo broker_id and angent_id only once here,
before the while loop, because the values are all the same */
while ($row = pg_fetch_array($sql_res)){
echo $order_number;
}
Assume broker and agent id numbers are each the same in every row. I don't want to echo them every time in the loop. I just want them to echo one time before the loop. Since they are the same, it does not matter which row they are echoed from.
I figured out a different way for a means to an end. It works well.
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
$count = 0;
while ($row = pg_fetch_array($sql_res)){
if ($count == 0) {
echo $broker_id;
echo $agent_id;
}
echo $order_number;
$count += 1;
}
I realize I'm echoing the broker and agent IDs inside the while loop, but it's only an echo the first time through, and I can display them at top. And then every unique order is echoed. Visually, it accomplished what was needed for the end user.
I ask in connection to this article:
How to get the columns names along with resultset in php/mysql?
$selecttable = mysql_query("SELECT * FROM $tablename WHERE (preis_bis <= '$price_upper' AND preis_bis > '$price_lower') LIMIT 1");
for ($i = 0; $i < mysql_num_fields($selecttable); $i++) {
$field_info = mysql_fetch_field($selecttable, $i);
// not WORKING
while($rowvalue = mysql_fetch_row($selecttable)) {
echo "<tr><td>Price: ".$rowvalue[$i]."</td></tr>";
}
echo "<tr><td style='border:1px solid #c0c0c0;padding:10px;'><!-- {$field_info->name} -->";
// get Logo and provider name
$select_getlogo = mysql_query("SELECT * FROM rrv_anbieter WHERE aid = '$field_info->name' LIMIT 1");
while($row_logo = mysql_fetch_object($select_getlogo)){
echo $row_logo->name.'<br><img src="images/'.$row_logo->logo.'" style="max-width: 200px;">';
}
#while($rowvalues2 = mysql_fetch_row($selecttable)) {
# foreach($rowvalues2 as $_column) {
# echo "<td>{$_column}</td>";
# }
#}
echo "</td></tr>";
}
I do not get it to get the correct row value within the "for" loop. Writing col names is working, but showing additionally the right value in same loop not.
Can someone help?
You need to iterate once more in the inner loop to get all rows of the table's columns.
while($rowvalue = mysql_fetch_row($selecttable)) {
foreach($rowvalue as $r){
echo "<tr><td> ".$r."</td></tr>";
}
}
$rowvalue[$i] showed rows incorrectly because it's following index based on the outer loop which is $i.
So basically the loop will print all rows of each column for n-times where n=number of all columns, not just the price column.
.
And you can also print all elements per-$rowvalue at once with :
while($rowvalue = mysql_fetch_row($selecttable)) {
$allElements = implode(",",$rowvalue ); // comma ',' is the separator
echo "<tr><td>". $allElements."</td></tr>";
}
}
I'm trying to get a value to be inserted into a table on a webpage if the value equals $i.
$i starts at a number and decreases every loop. i can get it to work but it outputs multiple lines for each $i equivalent to the results in the table
I've reworked the code using everyones feedback to get this.
Echo "<tr><th colspan='3'><center>$rackname</th> </tr>" ;
for ($i=$RUtotal; $i > 0; $i--)
{
echo" <tr class='rackbg'><td class='i'><center>$i</td>" ;
$sql1 = "SELECT racks.rackID, racks.rackname, devices.deviceID, devices.deviceName, racks.rackRU, devices.deviceRU, devices.RUcount
FROM racks LEFT JOIN devices ON racks.rackID = devices.rackID
WHERE devices.rackID = '$rackID'";
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_assoc($query1))
{
$deviceru = $row['deviceRU'];
$deviceID = $row['deviceID'];
$device = $row['deviceName'];
$deviceRUC = $row['RUcount'];
if ($deviceru == $i)
{
echo '<td class="device" rowspan='.$deviceRUC.'><a onclick=window.location="/devices.php?id='.$deviceID.'">'.$device.'</a></td><td rowspan='.$deviceRUC.'></td></tr>';
}
else
{
;
}
}
}
Echo "<tr class='rackb'><th colspan='3'>a</th></tr> " ;
This works to a degree (picture1) but when i add echo "" to the else statement it displays all wrong. (picture 2)
Any help would be greatly appreciated
Picture1 - http://imageshack.us/photo/my-images/263/examplewq.png/
Picture2 - http://imageshack.us/photo/my-images/269/example2jp.png/
I can't quite see what you're trying to do but what it looks like to me is that you want all the items from racks joined with their relevant device and displayed in order of deviceRU. Does this help:
echo "<tr><th colspan='3'><center><b>$rackname</th></tr>" ;
$sql1 = "SELECT racks.rackID, racks.rackname, devices.deviceID, devices.deviceName, racks.rackRU, devices.deviceRU, devices.RUcount
FROM racks LEFT JOIN devices ON racks.rackID = devices.rackID
WHERE racks.rackID = '$rackID' AND devices.deviceRU <= ".intval($RUtotal)."
ORDER BY devices.deviceRU;"
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1))
{
$deviceru = $row['deviceRU'];
$deviceID = $row['deviceID'];
$device = $row['deviceName'];
$deviceRUC = $row['RUcount'];
echo'<tr class="rackbg"><td class="i">'.$i.'</td><td class="device">'.$device.'</td><td></td></tr>';
}
I've used a LEFT (inner) JOIN in the SQL instead of the outer join that was there before as it'll return less results and might solve your problem. I've ordered the results by deviceRU and only returned results which have deviceRU less than or equal to $RUtotal (as I think the example was showing).
I've also removed the tags, these should be replaced by using CSS to centre either all td elements or centering class="device" and class="i" e.g.:
.device, .i {
text-align: center;
}
I've also swapped your abc to abc which is the correct format for a link.
Could you describe more of the context as it's difficult to see your intention from your post.
Mat
As Peetz said, you don't need nested loop. You need something like:
$i = $RUtotal;
// ...
while ($row = mysql_fetch_array($query1)) {
// ...
if ($deviceru == $i) {
// ...
} else {
// ...
}
// ...
$i--;
}
This is looping $i times, within the outer while loop. This means you are getting the table repeated over and over again.
I suggest you remove the outer while loop.
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