1

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

I want when I choose some value in a Select box to display a string for a number of times for example if I choosed the value 2 it will display a string twice.

this is the code I tried :

<!DOCTYPE HTML>
<html>
<head>
<script>
function checkIt()
{
    var getNum = document.getElementById("numb").value;

    //this_file.php ... im specifying for just. you specify this full code in any of file and specify the whole url path
    location.href="this_file.php?countIt="+getNum;
}
</script>
    <style type="text/css">
    .centrer
    {
        position: absolute;
        left: 50%;
        top: 50%;
        font-size:24px;
    }
    </style>

</head>
<body>
    <select name="nombres" id="numb" onchange="checkIt();">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>

<?php
if($_REQUEST["countIt"])
{
    $displayTimes = $_REQUEST["countIt"]; 
}
?>
   <div class="centrer">
    <?php
        $s = "Hello World! <br/>";
        for($i=0; $i<$displayTimes; $i++)
            echo $s;
    ?>
    </div>
</body>
</html>

but I have a problem :

Notice: Undefined variable: displayTimes in C:\Program Files\EasyPHP-12.1\www\site\Untitled-1.php on line 43

notice that the line 43 is : for($i=0; $i<$displayTimes; $i++)

and also another problem that when I select the "1" Value it does anything, and also when I select other value the selected value in the select box still the value "1" and I have another question isn't there any other way to do this without using JS only by using PHP ?

Community
  • 1
  • 1
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191

3 Answers3

6

$displayTimes would only be declared if the condition was met, it was caused by the following :

if($_REQUEST["countIt"]) <------------------- Condition 
{
    $displayTimes = $_REQUEST["countIt"];
}

Replace the above with :

$displayTimes = isset($_REQUEST["countIt"]) ? $_REQUEST["countIt"] : 0;
Musa
  • 96,336
  • 17
  • 118
  • 137
Baba
  • 94,024
  • 28
  • 166
  • 217
1

The variable $displayTimes must be set in order to use it. If $_REQUEST["countIt"] isn't set, then $displayTimes isn't set.

Change it to the following:

$displayTimes = isset($_REQUEST['countIt']) ? $_REQUEST['countIt'] : 0;

This way, if $_REQUEST['countIt'] isn't set it won't be executed.

noetix
  • 4,773
  • 3
  • 26
  • 47
1

This is a more clean code:

<?php
if(isset($_GET['countIt'])) {
  print '<div class="centrer">';
  $s = "Hello World! <br/>";
  for($i=0; $i<$_GET['countIt']; ++$i) echo $s;
  print '</div>';
}
?>

And check this JS code: http://jsfiddle.net/xPuEN/1/

Marian Zburlea
  • 9,177
  • 4
  • 31
  • 37
  • Thanks, but I sill have the problem that when I select the "1" Value it does anything, and also when I select other value the selected value in the select box still the value "1" – Renaud is Not Bill Gates Oct 19 '12 at 00:07