0

I have the following code, copied exactly from a exercise from a PHP book. I am having a problem with the value attribute which contains a php echo statement. According to the book, the first time the page is loaded the input boxes should be empty because the variables won't contain any data. Instead, I see something like this:

<br /><b>Notice</b>:  Undefined variable: investment in     <b>C:\xampp\htdocs\book_apps\ch02_future_value\index.php</b> on line <b>20</b><br />. 

Any suggestions?

<form action="display_results.php" method="post">

    <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>
5
  • 1
    It's probably a very old book. Which version of PHP is it teaching? Commented Jan 14, 2012 at 22:42
  • It's not only empty, it's undefined. Maybe your book was written for a less picky version of PHP. Commented Jan 14, 2012 at 22:43
  • The book is not old, it was published in 2010; it's "Murach's PHP and MySQL". Commented Jan 14, 2012 at 22:59
  • I replaced the php statement with <?php if (!empty($investement)) {echo $investement;} ?> and it seems to work properly now. Commented Jan 14, 2012 at 23:00
  • Is $investment ever created/defined? You're probably trying to echo a nonexisting variable. PS: you can use a shorthand of that if-statement: <?php echo (!empty($investment) ? $investment : ""); ?> Commented Feb 17, 2014 at 8:01

1 Answer 1

1

This is because you are expecting the register_globals directive to be set, while it is not.

This means you have to get $_POST['investement'] instead of $investment and you need to first check if it's been submitted:

$investment = array_key_exists('investment', $_POST) ? $_POST['investment'] : "";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.