While making a photo gallery I encountered a problem. With every photo I try to show how many comments it has, however if a photo has 0 comments it will give me an 'undefined offset' error. I have no idea what I am doing wrong because it does show that there are 0 comments.
This is the code of what is relevant to the problem:
(The problem occurres in the line: if($reacties[$i]==0){)
if((isset($_GET['vanafFoto'])) AND (intval($_GET['vanafFoto']>=0)) AND (intval($_GET['vanafFoto'] < $countFotos))){
$begin = intval($_GET['vanafFoto']);
if(($begin + $aantalFotos) <= $countFotos){
$eind = ($begin + $aantalFotos);
} // end if
else {
$eind = $countFotos;
} // end else
} // end if
else {
$begin = 0;
$eind = $aantalFotos;
} // end else
$countFotos = count($fotoArray);
// path naar echte foto
} // end else
echo "<table border='0' cellpadding='0' cellspacing='2'><tr><td ><b>" . $pathspatie . "</b> <small>(" . $count . ")</small>
<br><br><center><small>Pictures " . ($begin + 1) . " - " . $eind . "</small></center></td></tr></table>";
if(($begin - $aantalFotos) >= 0){
$navigation = "<a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin - $aantalFotos) . "'><</a> " . $navigation;
} // end if
if(($begin + $aantalFotos) < $count){
$navigation .= " <a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&vanafFoto=" . ($begin + $aantalFotos) . "'>></a>";
} // end if
echo $navigation . "<br><br>";
echo "</td></tr><tr>";
$fotonr = 1;
for($i=$begin; $i < $eind; $i++){
$thumb = str_replace($path2, $thumbPath, $fotoArray[$i]);
echo "<td align='center'><a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&fotoID=" . $i . "'><img border='0' src='" . $thumb . "' height='100'><br>";
echo "<small>reacties (";
if($reacties[$i]==0){ // error occurres here.
echo "0";
} // end if
else {
echo $reacties[$i];
} // end else
echo ")</small>";
echo "</a></td>";
$fotonr++;
if($fotonr == ($clm + 1)){
echo "</tr>\n<tr>";
$fotonr = 1;
} // end if
} // end for
If anyone can see what the problem is it would be great!
I did not understand you exact goal but maybe it is better to write one more check:
if(!isset($reacties[$i]) || $reacties[$i]==0){
echo "0";
}
Related
I'm trying to re-write this code so that it goes with the columns that are going to be user-defined. With this, my challenge consists of
a) Needs to select random starting item from array
b) Select the next random color from the original array that is not equivalent to the most recent items selected based the number: $intNotesColumn + 1
I was thinking a do-while statement nested inside another was appropriate for this but am unsure how to go about this. Here is my code so far:
$metroUIcolors = array( "#A30061", "#8200CC", "008987", "#A05000", "#B85A93", "#C07807", "#E51400", "#297A29" );
$metroUIcolorsLength = count($metroUIcolors);
$intNotesColumn = 3; // This will be user-defined later
// Now I query the SQL database to get my base-code
if ($result->num_rows > 0) {
// output data of each row
echo '<table border=0 valign=top>'
. '<tr>'
. '<td colspan=' . $intNotesColumn . '>' . '<h1>header</h1>' . '</td>'
. '</tr>'
. '<tr>';
$counterRank = 1;
while($row = $result->fetch_assoc()) {
echo "<td bgcolor=" . $metroUIcolors[rand(0, $metroUIcolorsLength - 1)]. ">"
. "<h2>" . $row["username"] . '</h2><br />'
. "<p class='notes'>" . $row["notes"] . "</p>"
. "<p class='footnotes'>"
. "<br />Last Reset: " . $row["lastReset"]
. '<br />Last Update: ' . $row['lastUpdate']
. '<br />SessionID: ' . $row["sessionID"]
. "<br />Counter = " . $counterRank . "</td>". '</p>';
if ($counterRank % $intNotesColumn == 0)
{
echo '</tr><tr>';
}
$counterRank++;
}
echo '</tr></table>';
} else{
echo "No Notes Found in databases";
}
Then, why don't you do it order picking one color at a time. You could use shuffle() so that there will be a different starting color everytime.
<?php
$counterRank = 1;
// shuffle the array
shuffle($metroUIcolors);
while($row = $result->fetch_assoc()) {
$rand_color = $counterRank % $metroUIcolorsLength;
echo "<td bgcolor=" . $metroUIcolors[$rand_color]. ">";
// everything else
$counterRank++;
}
?>
If you insist on doing the way you said, you may create an array $colorCount which has color codes as keys and count as values.
<?php
$counterRank = 1;
$colorCount = array_fill_keys($metroUIcolors, 0);
while($row = $result->fetch_assoc()) {
do {
$rand_color = $metroUIcolors[rand(0, $metroUIcolorsLength - 1)];
} while ($colorCount[$rand_color] > 5);
echo "<td bgcolor=" . $rand_color. ">";
// everything else
$counterRank++;
$colorCount[$rand_color] += 1;
}
?>
I have a php leaderboard and it works great, and works well with ties. Currently it will number users from 1st to last place (whichever # that is), and if there are ties, it lists them all out with the same number.
For example:
userC 2. userG 3. userA 3. userT 3. userJ 4. userW 5. userP
What I would like is for when there are ties, for the leaderboard to display a "(t)" next to the number, like so: (t) 3. userT
Here is my code, any help is appreciated:
<table cellpadding="4" cellspacing="0" class="table1" width="100%"><caption>
<h2>Leaderboard</h2>
</caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$i = 1;
$tmpScore = 0;
//show place #
foreach($playerTotals as $playerID => $stats) {
if ($tmpScore < $stats[score]) $tmpScore = $stats[score];
//if next lowest score is reached, increase counter
if ($stats[score] < $tmpScore ) $i++;
$pickRatio = $stats[score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($stats[score] / $possibleScoreTotal) * 100), 2) . '%';
//display users/stats
$rowclass = ((($i - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $i . '</b>. ' . $stats[userName] . '</td><td align="center">' . $stats[wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$tmpScore = $stats[score];
}
}
echo ' </div>' . "\n";
?>
</table>
Try this code... hope it will resolve your issue
<table cellpadding="4" cellspacing="0" class="table1" width="100%">
<caption><h2>Leaderboard</h2></caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$j = 1;
$tmpScore = 0;
//show place #
$tieflag=false;
for($i=0; $i<=count($playerTotals)-1; $i++) {
if(($i<count($playerTotals) && $playerTotals[$i][score]==$playerTotals[$i+1][score]) || ($i>0 && $playerTotals[$i][score]==$playerTotals[$i-1][score])) $tieflag=true;
$pickRatio = $$playerTotals[$i][score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($playerTotals[$i][score] / $possibleScoreTotal) * 100), 2) . '%';
$rowclass = ((($j - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . ($tieflag?'(t)'.$j:$j) . '</b>. ' . $playerTotals[$i][userName] . '</td><td align="center">' . $playerTotals[$i][wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$j++;
}
}
echo '</div>'. "\n";
?>
</table>
I'd create a new variable $placeholder. So:
if ( $i != 0 ) {
if ($tmpScore < $stats[score]) {
$tmpScore = $stats[score];
}
if ( $tmpScore == $stats[score] ) {
$placeholder = $i.'(t)';
} else if ($stats[score] < $tmpScore )
$placeholder = $++i;
}
} else {
$placeholder = $++i;
$firstScore = $stats[score];
$tmpScore = $stats[score];
}
Then instead of printing $i print $placeholder
so for the first time through you could do this in the echo:
//It makes more sense if you read it from bottom to top but I put it this way
//so you will not have to keep running through every condition when you will
//only evaluate the first condition most often
if ( $i != 0 && $i != 1 ) {
echo ;//Your normal print
} else if ( $i = 1 && $tmpScore != $firstScore ) {
echo '<b>'; //and the rest of the first line plus second line NOT a tie
} else if ( $i = 1 ) {
echo ' (t)'; //Plus the rest of your first line plus second line TIE
} else {
//This is your first time through the loop and you don't know if it's a tie yet so just
//Print placeholder and then wait to figure out the rest
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $placeholder;
}
I have a small time slot booking system, where I can click a link called: Reserve, and then I reserve that given time.
However, the page doesn't refresh after I've clicked on reserve. Therefore it's possible for a user to click the same reserve link twice. Whitch they shouldn't be able to.
if (isset ( $_GET ['reserved'] )) {
$sqlreserve = "INSERT INTO calendar (eventDate, timeslot) VALUES ('" . $dateToCompare . "','" . intval($_GET['t']) . "');";
$resultreserve = mysqli_query ( $mysqli1, $sqlreserve );
if ($resultreserve) {
header('Location: '.$_SERVER['PHP_SELF']);
} else {
echo "Event Failed to add";
}
}
If my insert works, then I call: header('Location: '.$_SERVER['PHP_SELF']);
I'm working on localhost, if that has anything to say?
EDIT:
The way I create my links and the text saying that a slot is booked is like this:
if (mysqli_num_rows ( $result ) == 0) {
echo "<a href='" . $_SERVER ['PHP_SELF'] . "?month=" . $month . "&day=" . $day . "&year=" . $year . "&t={$time}&v=true&f=true&reserved=true'><h3 style='color: rgb(255,0,0);'>Reserve</h3></a>";
} else {
echo "<h3>Not Available, taken by:</h3>";
while ( $row = mysqli_fetch_array ( $result ) ) {
echo "<br />";
}
}
EDIT. My Error:
Cannot modify header information - headers already sent by (output started.....)
for($i = 1; $i < $numDays; $i ++, $counter ++) {
$timeStamp = strtotime ( "$year-$month-$i" );
if ($i == 1) {
$firstDay = date ( "w", $timeStamp );
for($j = 0; $j < $firstDay; $j ++, $counter ++) {
echo "<td> </td>";
}
}
if ($counter % 7 == 0) {
echo "</tr><tr>";
}
$monthstring = $month;
$monthlength = strlen ( $monthstring );
$daystring = $i;
$daylength = strlen ( $daystring );
if ($monthlength <= 1) {
$monthstring = "0" . $monthstring;
}
if ($daylength <= 1) {
$daystring = "0" . $daystring;
}
$todaysDate = date ( "m/d/Y" );
$dateToCompare = $monthstring . '/' . $daystring . '/' . $year;
echo "<td align='center' ";
if ($todaysDate == $dateToCompare) {
echo "class='today'";
} else {
$sqlCount = "SELECT * FROM calendar WHERE eventDate='" . $dateToCompare . "'";
$noOfEvent = mysqli_num_rows ( mysqli_query ( $mysqli1, $sqlCount ) );
if ($noOfEvent >= 1) {
echo "class='event'";
}
}
echo "><a href='" . $_SERVER ['PHP_SELF'] . "?month=" . $monthstring . "&day=" . $daystring . "&year=" . $year . "&v=true'>" . $i . "</a></td>";
}
The line affected is:
echo "><a href='" . $_SERVER ['PHP_SELF'] . "?month=" . $monthstring . "&day=" . $daystring . "&year=" . $year . "&v=true'>" . $i . "</a></td>";
It is in another file where I have my calendar, in which I have links to the specific day that I wan't to book the timeslots fore:
Try this..
header('Location: '.$_SERVER['PHP_SELF']);
exit;
I think your code is continuing...
A more in-depth explanation can be found here: Why I have to call 'exit' after redirection through header('Location..') in PHP?
EDIT
It's clear now that Milen Georgiev answer is correct. You output content to the browser before you reach the header(); You need to move the if statement in the top part of your PHP code to avoid the header content error.
if (isset ( $_GET ['reserved'] )) {
$sqlreserve = "INSERT INTO calendar (eventDate, timeslot) VALUES ('" . $dateToCompare . "','" . intval($_GET['t']) . "');";
$resultreserve = mysqli_query ( $mysqli1, $sqlreserve );
if ($resultreserve) {
header('Location: '.$_SERVER['PHP_SELF']);
exit;
} else {
echo "Event Failed to add";
}
}
Do you send(output/echo) anything before header('Location: '.$_SERVER['PHP_SELF']); ?
If that is the case, you will have to turn the object buffer on. Using header, you always have to send the headers first or it will not work.
I have a simple php script that counts the number of pages in a manga script :
$omv_pager = "";
$omv_pager .= "<div class=\"well\">\n";
$omv_pager .= "<span>Manga <select class=\"form-control\" style='margin-bottom:10px;' name=\"manga\" onchange=\"change_manga(this.value)\">";
$omv_pager .= "<option class=\"form-control\" value=\"0\">Selecione TÃtulo do Manga...</option>";
for ($i = 0; $i < count($mangas); $i++) {
$m = $mangas[$i];
$omv_pager .= "<option value=\"" . omv_encode($m) . "\"" . (($m == $manga) ? " selected=\"selected\"" : "") . ">" . $m . "</option>";
}
$omv_pager .= "</select></span>\n";
if ($manga) {
if ($chapter) {
$omv_pager .= "<span>Chapter <select name=\"chapter\" onchange=\"change_chapter('$manga_escaped', this.value)\">";
for ($i = 0; $i < count($chapters); $i++) {
$cnumber = $chapters[$i]["number"];
$omv_pager .= "<option value=\"" . omv_encode($cnumber) . "\"" . (($cnumber == $chapter_number) ? " selected=\"selected\"" : "") . ">" . $cnumber . (isset($chapters[$i]["title"]) ? (" - " . $chapters[$i]["title"]) : "") . "</option>";
}
$omv_pager .= "</select></span>\n";
if ($page) {
$prevhtml = "";
if ($page <= 1) {
$prevhtml = "<img src=\"http://www.leitor.tk/themes/default/no-previous.png\" alt=\"\" />";
} else {
$prevhtml = "<img src=\"http://www.leitor.tk/themes/default/previous.png\" alt=\"Previous Page\" title=\"Previous Page\" />";
}
$nexthtml = "";
if ($page >= count($pages)) {
$nexthtml = "<img src=\"http://www.leitor.tk/themes/default/no-next.png\" alt=\"\" />";
} else {
$nexthtml = "<img src=\"http://www.leitor.tk/themes/default/next.png\" alt=\"Next Page\" title=\"Next Page\" />";
}
$omv_pager .= "<span>$prevhtml Page <select name=\"page\" onchange=\"change_page('$manga_escaped', '$chapter_number_escaped', this.value)\">";
for ($p = 1; $p <= count($pages); $p++) {
$omv_pager .= "<option value=\"" . $p . "\"" . (($p == $page) ? " selected=\"selected\"" : "") . ">" . $p . "</option>";
}
$omv_pager .= "</select> of " . count($pages) . " $nexthtml</span>\n";
}
}
}
$omv_pager .= "</div>\n";
echo $omv_pager;
What I want to do is, in the last page change the name of the to "end"
e.g : 1-2-3-4-5-6-7-8-9-10-11-12-end
And thanks to all of you guys.
Try with:
">" . ($p == count($pages) ? "end" : $p) . "</option>"
instead of
">" . $p . "</option>"
For optimization reasons you might want to buffer count($pages) into a variable before the for.
I'm looking to limit to the first 5 results returned here.
This works, but it does not limit the data set:
<?php
foreach($sxml->status as $status){
$name = $status->user->name;
$image =$status->user->profile_image_url;
$update =$status->text;
$url = "http://twitter.com/" .$status->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
?>
I've tried this:
<?php
for($n = 0; $n <= 5; $n++){
$name = $sxml->$status[$n]->user->name;
$image = $sxml->$status[$n]->user->profile_image_url;
$update = $sxml->$status[$n]->text;
$url = "http://twitter.com/" . $sxml->$status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
?>
and am really kind of unsure why it doesn't work. If I simply do:
<?php echo $sxml->status[0]->user->name ?>
then I get the proper result. But when attempting it within the for loop, I get NULL.
Perhaps some kind of while? A different setup altogether? Thanks so much for any help you can give on this.
Change this:
for($n = 0; $n <= 5; $n++){
$name = $sxml->$status[$n]->user->name;
$image = $sxml->$status[$n]->user->profile_image_url;
$update = $sxml->$status[$n]->text;
$url = "http://twitter.com/" . $sxml->$status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
To this:
for($n = 0; $n <= 5; $n++){
$name = $sxml->status[$n]->user->name;
$image = $sxml->status[$n]->user->profile_image_url;
$update = $sxml->status[$n]->text;
$url = "http://twitter.com/" . $sxml->status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
You accidentally were writing this:
<?php echo $sxml->$status[0]->user->name ?>
Where it was trying to us $status[0] as a variable variable and of course, that doesn't exist and is thus undefined/null.
If you had something that works, why overcomplicate things by changing everything? Just limit the processing to the first N entries.
$i = 0;
foreach ($sxml->status as $status) {
if (++$i > 5) {
// stop after 5 loops
break;
}
// the rest is identical
}
Btw, $n = 0; $n <= 5; $n++ will limit to the first 6 entries, not 5.
$n = 0; $n < 5; $n++ will do what you asked for.
Don't you mean
$n = 0; $n < 4; $n++
I've also tried this, and it works great :-)
foreach ($xml->item as $item) {
if (++$i > 5) { break; }
$item->title . '';
} //foreach()
Note I'm not using $i = 0; it seems to know that by default ;-)
I hope this helps some one.