-1

I made a PHP code to add a list of buttons on my website, but it doesn't work, it doesn't update the number and stays on the same integer

I already tried modifying the code and changing some things.

<?php 
$capnum1 = 1;
$capbtn = '<a href="#cap'.$capnum1.'"><button class="w3-btn bg" onclick="openCity('."cap".$capnum1."'".')">'.$capnum1."</button></a>";
$capbtn2 = '<a href="#cap'. $capnum1++ . '"><button class="w3-btn bg" onclick="openCity('."cap". $capnum1++ ."'".')">'. $capnum1++ ."</button></a>";

echo $capbtn;

while($capnum1 <= 5){
    $capnum1++;
    echo $capbtn;
}

?>

I expected it to be 1,2,3,4,5 but it was 1,1,1

Ganesa Vijayakumar
  • 2,422
  • 5
  • 28
  • 41
stake2
  • 5
  • 2
  • 1
    The problem is that the value you've declared for use in $capbtn is in line 1. The value in the loop has no effect on $capbtn – Russ J Nov 06 '19 at 03:54
  • 1
    You might want to use a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) for that or look at [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Nov 06 '19 at 03:55

3 Answers3

0

You did not output capbtn2. So I figured out to output it. And then,I fixed your code.

<?php
$capnum1 = 1;
$capbtn = '<a href="#cap'.$capnum1.'"><button class="w3-btn bg" onclick="openCity('."cap".$capnum1."'".')">'.$capnum1."</button></a>";
$capbtn2 = '<a href="#cap'.$capnum1. '"><button class="w3-btn bg" onclick="openCity('."cap". $capnum1++ ."'".')">'. $capnum1++ ."</button></a>";

echo $capbtn;
echo $capbtn2;

while($capnum1 <= 5){
    echo '<a href="#cap'.$capnum1.'"><button class="w3-btn bg" onclick="openCity('."cap".$capnum1."'".')">'.$capnum1."</button></a>";
    $capnum1++;
}
?>
0

Just remove the $capbtn2 since it is not required. You can check with the code below:

<?php
    $capnum1 = 0;

    while($capnum1 <= 4) {
        $capnum1++;
        $capbtn = '<a href="#cap'.$capnum1.'"><button class="w3-btn bg" onclick="openCity('."cap".$capnum1."'".')">'.$capnum1."</button></a>";
        echo $capbtn;
    }  
?>

Check out the link for results: Button Results

0

Your $capbtn and $capbtn2 have static value. You should use function like this.

$capnum1 = 1;

function showButton() {
    return '<a href="#cap'.$capnum1.'"><button class="w3-btn bg" onclick="openCity('."cap".$capnum1."'".')">'.$capnum1."</button></a>"; 
}

echo showButton();

while($capnum1 <= 5){
    $capnum1++;
    echo showButton();
}

?>
Allen Haley
  • 639
  • 5
  • 21