Question about a tutorial

I decided this weekend to try to learn PHP. I purchased a book called Murach’s PHP and MySQL and am following the tutorials. XAMPP seems to be installed just fine, and simple includes and calls to a database work as expected. I have, however, come across one example that is yielding an odd error. The following code is meant to present a form for data entry:

Future Value Calculator

Future Value Calculator

<?php if (!empty($error_message)) { ?>

<?php echo $error_message; ?>

<?php } // end if ?>
    <div id="data">
        <label>Investment Amount:</label>
        <input type="text" name="investment"
               value="<?php echo $investment; ?>"/><br />

        <label>Yearly Interest Rate:</label>
        <input type="text" name="interest_rate"
               value="<?php echo $interest_rate; ?>"/><br />

        <label>Number of Years:</label>
        <input type="text" name="years"
               value="<?php echo $years; ?>"/><br />
    </div>

    <div id="buttons">
        <label>&nbsp;</label>
        <input type="submit" value="Calculate"/><br />
    </div>

</form>
</div>

When I visit the page, the text boxes, which are expected to be empty, are full of errors such as this:

Notice: Undefined variable: investment in C:\xampp\htdocs\book_apps\ch02_future_value\index.php on line 20

Interestingly, when I remove the errors from the text boxes and enter valid data, the page returns just fine.

I had rather expected that the books examples would be working correctly, so I double checked the function of XAMPP and MySQL. I’m a novice though, and I’m not certain if I’m on the right track.

Does anybody have some insight or advice?

[code]<?php error_reporting(E_ALL); ?>

Future Value Calculator

Future Value Calculator

<?php if(isset($investment)){ }else{ $investment = ''; } if(isset($interest_rate)){ }else{ $interest_rate = ''; } if(isset($years)){ }else{ $years = ''; } ?>
<?php if (!empty($error_message)) {
   echo('<p class="error">'.$error_message.'</p>');
 } 

// end if ?>

    <div id="data">
        <label>Investment Amount:</label>
        <input type="text" name="investment" value="<?php echo $investment; ?>"/><br />

        <label>Yearly Interest Rate:</label>
        <input type="text" name="interest_rate" value="<?php echo $interest_rate; ?>"/><br />

        <label>Number of Years:</label>
        <input type="text" name="years" value="<?php echo $years; ?>"/><br />
    </div>

    <div id="buttons">
        <label>&nbsp;</label>
        <input type="submit" value="Calculate"/><br />
    </div>

</form>
</div>
[/code]

What was happening is when first visiting the site, $interest_rate isn’t set as a variable.
So check if its set, if it isn’t set it to something.
Also your error message would be cleaner if it was incased in 1 <?php instead of multiples.

Sponsor our Newsletter | Privacy Policy | Terms of Service