dtommy79 Posted September 27, 2016 Share Posted September 27, 2016 Hi,I created a simple script that converts miles to kilometer. I added it to an HTML file and it works fine, but when I load the page (and there is nothing to convert) it gives me an error: Notice: Undefined index: mile in F:\wamp64\www\exchange\convert.php on line 130 So basically what I want is to display nothing on page load or if there is nothing in the input field. Here is my code: <h3 class="section-heading">Convert Miles to Kilometer II.</h3> <hr class="primary"> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="margin-top: 20px;"> <p>Add Miles: <input type="text" class="form-control" placeholder="miles" name="mile" size="2" /> </p> <p> <input type="submit" class="btn btn-primary" value="Submit" /> </p> </form> <?php $miles = $_POST['mile']; //This is line 130 // How many km is one mile? $onemile = 1.609344; $totalkm = $miles * $onemile; print "<p>$miles miles is $totalkm kilometer.</p>"; ?> Thanks in advance Quote Link to comment Share on other sites More sharing options...
Psycho Posted September 27, 2016 Share Posted September 27, 2016 (edited) First a tip: Create your logic (i.e. PHP ) at the top of the script and create variables for the output. Then put the presentation (i.e. HTML) at the bottom of the script using just echo's for the applicable output content. For your issue, do a check to see if the value was submitted before trying to access the POST variable. <?php $output = ''; $miles = ''; if(isset($_POST['mile'])) { // How many km is one mile? $onemile = 1.609344; $miles = floatval($_POST['mile']); $totalkm = $miles * $onemile; $output = "<p>$miles miles is $totalkm kilometers.</p>"; } ?> <h3 class="section-heading">Convert Miles to Kilometer II.</h3> <hr class="primary"> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="margin-top: 20px;"> <p>Add Miles: <input type="text" class="form-control" placeholder="miles" name="mile" size="2" value="<?php echo $miles; ?>" /> </p> <p><button type="submit" class="btn btn-primary">Submit</button></p> </form> <?php echo $output; ?> Edited September 27, 2016 by Psycho Quote Link to comment Share on other sites More sharing options...
dtommy79 Posted September 27, 2016 Author Share Posted September 27, 2016 Thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.