简体   繁体   中英

Receiving Error: Notice: Undefined variable – but already defined

I dont know what im doing wrong. But i get this

Notice: Undefined variable: num1 in D:\\Programs\\XAMPP\\htdocs\\homework\\addsub.php on line 15`

<?php 
    if(isset($_POST['sub']))
    {
        $num1=$_POST['t1'];
        $num2=$_POST['t2'];
        if ($_POST['sub']=="+") {
            $res= $num1 + $num2;
        }
        elseif($_POST['sub']=="-"){
            $res = $num1-$num2;
        }
    }
 ?>
<form action="addsub.php"  method="POST">
    <input type="text" name="t1" value="<?php echo $num1;?>"><br>
    <input type="text" name="t2" value="<?php echo $num2;?>"><br>
    <input type="text" name="res" value="<?php echo $res;?>"><br>
    <input type="submit" name="sub" value="+">
    <input type="submit" name="sub" value="-">
</form>

When I use $num1 or $num2 in textbox values, it shows error. One of my friends used this same code on his laptop but he is using much older version of Xampp. It works fine but later versions of Xampp gives this error. I am using Xampp v3.2.1 .

Or initialize the variable if it doesn't exist, like so:

<?php
if (!isset($num1)) {
    $num1 = '';
}

Then your HTML could remain unchanged.

The reason I recommend this approach is that it creates clean code - the HTML will always display the value of $num1 and if you choose to initialize it to a different value later, it should be easier to find in the PHP.

use isset to check variable exist or not.

example

<input type="text" name="t1" value="<?php echo isset($num1)?$num1:""; ?>"><br>

You set the $num1 variable only when,

if(isset($_POST['sub']))

So, if the $_POST['sub'] is not there the variable is undefined!

Here is the code, which may help you:

<?php 
    var $res="";
    var $num1="";
    var $num2="";
    if(isset($_POST['sub']))
    {
        $num1=$_POST['t1'];
        $num2=$_POST['t2'];
        if ($_POST['sub']=="+") {
            $res= $num1 + $num2;
        }
        elseif($_POST['sub']=="-"){
            $res = $num1-$num2;
        }
    }
 ?>

<form action="addsub.php"  method="POST">
    <input type="text" name="t1" value="<?php echo $num1;?>"><br>
    <input type="text" name="t2" value="<?php echo $num2;?>"><br>
    <input type="text" name="res" value="<?php echo $res;?>"><br>
    <input type="submit" name="sub" value="+">
    <input type="submit" name="sub" value="-">
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM