I have created the following script for determining which page numbers to display for navigation on my website.
// query the database
$statement = $connect->prepare("SELECT COUNT(report_number) FROM reports");
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
$rowCount = $result["COUNT(report_number)"];
$pgCount = ceil($rowCount / 10);
// fetch the corresponding entries from the database
if (!isset($pgParamArray["page"]) || $pgParamArray["page"] === $pgCount) {
$pgParamArray["page"] = $pgCount;
$sql = "SELECT * FROM reports ORDER BY report_number DESC LIMIT 10";
} elseif (isset($pgParamArray["page"])) {
$offset = ($pgCount - $pgParamArray["page"]) * 10;
$sql = "SELECT * FROM reports ORDER BY report_number DESC LIMIT " . $offset . ",10";
}
// calculate and display the appropriate page numbers
$upperDiff = $pgCount - $pgParamArray["page"];
$lowerDiff = $pgParamArray["page"] - 1;
for ($i = 0; $i < 5; $i++) {
$pgNo = 0;
if ($pgParamArray["page"]+2 <= $pgCount && $pgParamArray["page"]-2 >= 1) {
$pgNo = $pgParamArray["page"] + ($i - 2);
} elseif ($pgCount < 5) {
$pgNo = $i+1 <= $pgCount ? $i+1 : 0;
} elseif ($upperDiff < $lowerDiff && $upperDiff < 2 && $upperDiff >= 0) {
$pgNo = ($pgCount - 4) + $i;
} elseif ($lowerDiff < $upperDiff && $lowerDiff < 2 && $lowerDiff >= 0) {
$pgNo = $i + 1;
} else {
$pgNo = ($pgCount - 4) + $i;
}
if ($pgNo > 0) {
if ($pgNo !== $pgParamArray["page"]) {
$pgNoArray[] = ""
. "<li><div><a href='http://www.somewebsite.com/index.php/?page="
. $pgNo
. "'>"
. $pgNo
. "</a></div></li>";
} else {
$pgNoArray[] = ""
. "<li><div style='background:#333'>"
. $pgNo
. "</div></li>";
}
}
}
When I set $pgParamArray["page"] = $pgCount = ceil($rowCount/10), I have noticed that the foremost variable is still treated as a float. My question is why is $pgParamArray["page"] of type float even though ceil($rowCount/10) obviously returns an integer?
PHP's ceil returns a float according to their documentation.
Their rationale:
value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.
This isn't just PHP that does this - C++ and Java both return floating point values for their ceiling functions.
Related
I've created a questionnaire with three categories. Each possible answer in the questionnaire corresponds with one of the categories. I have three admin numeric fields where I add the number of answers selected from each category (fields 121, 122, 123). This part of the form is working. I'd like to compare the totals from these fields to see which is greatest and then return that result to a hidden field (field 126). So far my code is triggering a critical error when I submit the form.
add_filter("gform_pre_submission_9", "find_highest_percent");
function find_highest_percent ($vata, $pitta, $kapha, $form) {
$total = 0;
$vata = $_POST["input_121"] ;
$pitta = $_POST["input_122"] ;
$kapha = $_POST["input_123"] ;
$total = $vata + $pitta + $kapha;
$vata_percent = ($vata / $total) * 100;
$pitta_percent = ($pitta / $total) * 100;
$kapha_percent = ($kapha / $total) * 100;
if (abs($vata - $kapha) <= 10) {
$result = "Vata-Kapha";
} elseif (abs($vata - $pitta) <= 10) {
$result = "Vata-Pitta";
} elseif (abs($pitta - $kapha) <= 10) {
$result = "Pitta-Kapha";
} elseif (abs($vata - $pitta) <= 10 && abs($vata - $kapha) <= 10 && abs($pitta - $kapha) <= 10) {
$result = "Tri-Doshic";
} else {
if ($vata > $pitta && $vata > $kapha) {
$result = "Vata";
} elseif ($pitta > $vata && $pitta > $kapha) {
$result = "Pitta";
} else {
$result = "Kapha";
}
}
$_POST["input_126"] = $result;
}
I've tested by removing all calculations and simply returning the number 100 but this also triggers the error. Grateful for any suggestions.
Does it help to set the variables to integers?
$vata = (int)$_POST["input_121"] ;
$pitta = (int)$_POST["input_122"] ;
$kapha = (int)$_POST["input_123"] ;
I have a problem and that is I want to create a link on a website like people can click the link to show certain products only depending on percentage. like for example, i have a column in my database with discount percentage and it will show min discount and max discount. assuming we have min and max discount. $min=12 and $max=94; and I want to put them in links to show only products with certain discounts only like filtering. below is the example of the link.
<a href="#">12% to 20%</a
21% to 30%
31% to 40% and so on until it reaches
81% to 90% and the last will be
91% to 94%
smallest and largest numbers will be coming from a column from database and they can change frequently. i came up with solution and its working fine but my code is too long and its like I took to many steps which could be done in few lines of code. I have pasted my working code below but I am sure this can be reduced to few lines of code.
$catsql25 = "SELECT MAX(down_percentage) as largest FROM hot_deals";
$catquery25 = mysqli_query($conn, $catsql25);
while ($row25 = mysqli_fetch_array($catquery25, MYSQLI_ASSOC)){
$largest_number = $row25['largest'];
}
$catsql26 = "SELECT MIN(down_percentage) as smallest FROM hot_deals";
$catquery26 = mysqli_query($conn, $catsql26);
while ($row26 = mysqli_fetch_array($catquery26, MYSQLI_ASSOC)){
$smallest_number = $row26['smallest'];
}
$array_tens = array(10,20,30,40,50,60,70,80,90,100);
foreach ($array_tens as $value){
if(($value - $smallest_number <= 10) && ($value - $smallest_number > 0)){
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++){
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
}
foreach ($array_tens as $value2){
if(($largest_number - $value2 < 10) && ($largest_number - $value2 > 0)){
$lsst = $value2 + 1;
if($lsst != $largest_number){
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
}
elseif($lsst == $largest_number){
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
I know its all mess but..
Thanks.
First thing you could do is only one SQL Query :
$catsql = "SELECT MAX(down_percentage) as largest, MIN(down_percentage) as smallest FROM hot_deals";
And then you'll need only one loop :
$catquery = mysqli_query($conn, $catsql);
while ($row = mysqli_fetch_array($catquery, MYSQLI_ASSOC)){
$largest_number = $row['largest'];
$smallest_number = $row['smalest'];
}
After that, you could make only one foreach loop. The two "if" conditions could be in the same loop :
foreach ($array_tens as $value) {
if (($value - $smallest_number <= 10) && ($value - $smallest_number > 0)) {
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++) {
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
if (($largest_number - $value < 10) && ($largest_number - $value > 0)) {
$lsst = $value + 1;
if ($lsst != $largest_number) {
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
} elseif ($lsst == $largest_number) {
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
To make it more readable, you could also comment your code to know what do what.
This and a good indentation and you're right.
Hope it helps.
If I'm trying to display a table (which I've accomplished with a while loop) but also display a count underneath it. Do I add another while loop? Or a seperate for loop? How would I do that? I need to count the number of performances (Ive got that working) but it wont tally the number of performances in Asheville. How do I target that variable by itself?
> <?php print ("<h1>Upcoming Performances in 2015</h1>"); print
> ("<table border =\"1\">"); print("<tr><th align =
> \"left\">Date</th><th align = \"left\">Venue</th><th align =
> \"left\">City</th><th align = \"right\">Ticket Price</th></tr>");
>
> $count = 0; $ashevilleCount = 0; $eventFile =
> fopen("performances.txt", "r"); $schedule = fgets($eventFile);
>
>
> while(!feof($eventFile)) { list($date, $venue, $city, $ticketPrice) = explode(":", $schedule);
> print("<tr><td>$date</td>"); print("<td>$venue</td>"); print("<td>$city</td>"); print("<td>$ticketPrice</td>");
> $schedule = fgets($eventFile);
> }
>
> for($count = 1; $count <= 5; $count = $count + 1) { $total = fgets($eventFile); $count = $count + $total;
> }
> if ($city == Asheville)
> $ashevilleCount = $ashevilleCount + $count;
>
>
>
>
>
> fclose($eventFile);
> print ("</table>");
>
> print ( "<p class=\"alert\">Lower cost venues are marked with
> *</p>"); print ("<p>NUMBER OF PERFORMANCES: $count</p>"); print ("<p>NUMBER OF PERFORMANCES IN ASHEVILLE: $ashevilleCount</p>");
>
>
>
>
> ?>
You need to take a look at your if statements.
if($condition === true){
//executes if $condition is true
} elseif($condition === 1) {
//executes if $condition is 1
} elseif($condition === 2 || $condition === 3){
//executes if $condition is 2 OR condition is 3
} elseif($condition === 4 && $otherCondition !== "foo"){
//executes if $condition is 4 AND $otherCondition is NOT "foo"
} else {
//executes if no other statements are true
}
This piece of code:
elseif
($charType == human or dwarf and $goldSpent <= 10)
$supplyTokens = $_POST['supplyTokens'] + 10;
Needs to look like:
} elseif( ( $charType=="human" || $charType=="dwarf" ) && $goldSpent <= 10) {
$supplyTokens = $_POST['supplyTokens'] + 10;
}
Remember:
|| = "or"
&& = "and"
test != "test" - make sure your strings are enclosed in quotation marks
See:
http://php.net/manual/en/control-structures.if.php
http://php.net/manual/en/control-structures.elseif.php
http://php.net/manual/en/language.operators.comparison.php
Here's your code cleaned up. What was done:
Changed all the print() commands to concatenated echos.
Fixed the conditionals
You don't need to check for $goldSpent <= 10 in your elseifs as you have already checked that by not being in $goldSpent > 10
I personally prefer || and && as opposed to or and and
Added curly brackets {}
Thing to consider:
What would happen if any of those $_POST values are empty??
<?php
$charName = $_POST['charName'];
$charType = $_POST['charType'];
$healthTokens = $_POST['healthTokens'];
$expTokens = $_POST['expTokens'];
$supplyTokens = $_POST['supplyTokens'];
$goldSpent = $healthTokens / 10 + $expTokens / 2 + $supplyTokens / 25;
if ($goldSpent > 10) {
echo "<h1>HEY THERE, $charName!</h1>" .
"<p>YOU SPENT MORE GOLD THAN YOU HAVE!</p>" .
"<p>GO BACK AND TRY THAT AGAIN - YOU HAVE 10 GOLD PIECES..</p>";
} elseif ($charType == 'elf') {
$healthTokens = $_POST['healthTokens'] + 5;
} elseif ($charType == 'wizard') {
$expTokens = $_POST['expTokens'] + 2;
} elseif ($charType == 'human' || $charType == 'dwarf') {
$supplyTokens = $_POST['supplyTokens'] + 10;
}
$totalGold = 10;
$goldLeft = $totalGold - $goldSpent;
echo "<h1>You have created $charName the $charType!</h1>" .
"<p>$charName has <strong>$healthTokens</strong> health tokens," .
"<strong>$expTokens</strong> experience tokens, and" .
"<strong>$supplyTokens</strong> supply tokens.</p>" .
"<p>You received some bonus tokens! :)</p>" .
"<p>$charName has spent <strong>$goldSpent</strong> gold pieces, " .
"and has <strong>$goldLeft</strong> gold pieces left.</p>";
Good day, I was tasked to make a variable counter in php.
Im stuck at the last stage. And that is to display the total number of positive values. I used the count() in php, but it's not giving me the total number. is there a way that i can get the summation of the value that is is count()?
if ($start < $end)
{
for($ctr = $start; $ctr<=$end; $ctr++)
{
if ($ctr == 0)
{
echo " <br/ >there is a zero <br/ >";
}
else if ($ctr <=0)
{
echo count($ctr) . " negative value" ;
}
else if($ctr >=0)
{
echo count($ctr) . " positive value ";
}
}
$zero = $pos = $neg = 0;
for($ctr = $start; $ctr<=$end; $ctr++)
{
switch(true){
case $ctr==0: $zero++; break;
case $ctr<0: $neg++; break;
case $ctr>0: $pos++; break;
}
}
if($zero)
echo "there is a zero<br/>";
if($pos)
echo "$pos positive values<br/>" ;
if($neg)
echo "$neg negative values<br/>" ;
Better way is without any loop:
function test($start, $end) {
echo "Test of [$start, $end]:\n";
if ($isThereZero = $start * $end <= 0) {
echo "There is zero\n";
}
if ($start < 0) {
$negatives = $isThereZero ? -$start : -$start+$end;
echo "$negatives negative values\n";
}
if ($end > 0) {
$positives = $isThereZero ? $end : $end - $start;
echo ($positives)." positive values\n";
}
}
test(-12, 5);
test(-12, -5);
test(5, 12);
test(0, 0);
Try that :
$zer = 0;
$pos = 0;
$neg = 0;
if ($start < $end)
{
for($ctr = $start; $ctr<=$end; $ctr++)
{
if ($ctr == 0)
{
$zer++;
}
else if ($ctr < 0)
{
$neg++;
}
else if($ctr > 0)
{
$pos++;
}
}
echo $zer . " zero value" ;
echo $neg . " negative value" ;
echo $pos . " positive value ";
Just for fun, this could be done without a loop. This is a bit tricky and also a bit far from the initial question :
Demo
$start = -3;
$end = 5;
echo ($start <= 0 && $end >= 0 ? "1" : "0")." zero value\n";
echo ($start < 0 && $start <= $end ? (-$start-($end > -1 ? 0 : -$end-1)) : "0"). " negative value\n";
echo ($end > 0 && $start <= $end ? ($end-($start < 1 ? 0 : $start-1)) : "0"). " positive value\n";
else if($ctr >=0)
{
$cnt++; //or $cnt+=1;
}
Then use $cnt++ for no of count for positive vales
I have a pagination system, that fetches all of the results from a database & then loads them into a pagination.
Let's say I set the limit to 5 results per page, it will generate more pages, and order the results by date & time.
But I have a problem, my system always missing the most new result (by date/time) in the database, I have no idea why..
This is the code:
// how many rows to show per page
$rowsPerPage = 10;
// by default we show first page
$page_num = 1;
// if $_GET['page'] defined, use it as page number, $_GET gets the page number out of the url
//set by the $page_pagination below
if(isset($_GET['page'])){$page_num = $_GET['page'];}
//the point to start for the limit query
$offset = $page_num;
// Zero is an incorrect page, so switch the zero with 1, mainly because it will cause an error with the SQL
if($page_num == 0) {$page_num = 1;}
// counting the offset
$sql = "SELECT * FROM comments ORDER BY date, time desc LIMIT $offset, $rowsPerPage";
$res = $pdo->query($sql);
// how many rows we have in database
$sql2 = "SELECT COUNT(comment_id) AS numrows FROM comments";
$res2 = $pdo->query($sql2);
$row2 = $res2->fetch();
$numrows = $row2['numrows'];
// print the random numbers
while($row = $res->fetch())
{
//Echo out your table contents here.
echo $row[1].'<BR>';
echo $row[2].'<BR>';
echo '<BR>';
}
// how many pages we have when using paging?
$numofpages = ceil($numrows/$rowsPerPage);
// print the link to access each page
$self = "events.php?";
$page_pagination = '';
if ($numofpages > '1' ) {
$range = 10; //set this to what ever range you want to show in the pagination link
$range_min = ($range % 2 == 0) ? ($range / 2) - 1 : ($range - 1) / 2;
$range_max = ($range % 2 == 0) ? $range_min + 1 : $range_min;
$page_min = $page_num- $range_min;
$page_max = $page_num+ $range_max;
$page_min = ($page_min < 1) ? 1 : $page_min;
$page_max = ($page_max < ($page_min + $range - 1)) ? $page_min + $range - 1 : $page_max;
if ($page_max > $numofpages) {
$page_min = ($page_min > 1) ? $numofpages - $range + 1 : 1;
$page_max = $numofpages;
}
$page_min = ($page_min < 1) ? 1 : $page_min;
if ( ($page_num > ($range - $range_min)) && ($numofpages > $range) ) {
$page_pagination .= '<a class="num" title="First" href="'.$self.'page=1"><</a> ';
}
if ($page_num != 1) {
$page_pagination .= '<a class="num" href="'.$self.'page='.($page_num-1). '">Previous</a> ';
}
for ($i = $page_min;$i <= $page_max;$i++) {
if ($i == $page_num)
$page_pagination .= '<span class="num"><strong>' . $i . '</strong></span> ';
else
$page_pagination.= '<a class="num" href="'.$self.'page='.$i. '">'.$i.'</a> ';
}
if ($page_num < $numofpages) {
$page_pagination.= ' <a class="num" href="'.$self.'page='.($page_num + 1) . '">Next</a>';
}
if (($page_num< ($numofpages - $range_max)) && ($numofpages > $range)) {
$page_pagination .= ' <a class="num" title="Last" href="'.$self.'page='.$numofpages. '">></a> ';
}
}
echo $page_pagination.'<BR><BR>';
echo 'Number of results - '.$numrows ;
echo ' and Number of pages - '.$numofpages.'<BR><BR>';
$res2->closeCursor();
Question:
What have I done wrong? I cant' really see anything wrong, but I always get this error:
Notice: Undefined variable: page_pagination
Line:
echo $page_pagination.'<BR><BR>';
It always happens on a different line, depends on the results amount, but to fix that I need to declare page_pagination = ''; before the whole thing.
How can I fix this and what is causing this problem?
Thanks.
Your $offset is being set to 1. The newest one is always missing because it's going form 1-10 rather than 0-9. Index starts at 0. The following should work.
$offset = ($rowsPerPage * $page_num) - $rowsPerPage;