benjahnee Posted January 30, 2013 Share Posted January 30, 2013 hi guys Please help me as i am very new to this,( please explain things in simple terms) I have attempted to to write a code that will convert miles to kilometers, the file name is convert.htm, here is my code - </head> <body> <form method="POST" action="convert.htm"> Miles: <input type="text" name="miles" /><br> <input type="submit" name="submit" value="Convert!" /> </form> <?php function miles2kms($miles) { $ratio = 1.609344; $kms = $miles * $ratio; return $kms; } ?> </body> </html> could sumone please tell me what else i have to add to this code so that when a user submits an amount of miles, the conversion is posted to the same page. thanks so much Quote Link to comment https://forums.phpfreaks.com/topic/273824-first-php-code-please-help-me/ Share on other sites More sharing options...
PaulRyan Posted January 30, 2013 Share Posted January 30, 2013 Try this: <?PHP function miles2kms($miles) { $ratio = 1.609344; $kms = $miles * $ratio; return $kms; } //### If the form has been posted, process data if(strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') { //###Assign and santize data $miles = (float)$_POST['miles']; //### Convert value and assign it $converted = miles2kms($miles); } //### IF the converted value is set, display text if(isSet($converted)) { echo $miles .' miles, converts to '. $converted .' kilometres'; } ?> <form method="POST" action="?"> Miles: <input type="text" name="miles" /><br> <input type="submit" name="submit" value="Convert!" /> </form> Quote Link to comment https://forums.phpfreaks.com/topic/273824-first-php-code-please-help-me/#findComment-1409133 Share on other sites More sharing options...
Christian F. Posted January 30, 2013 Share Posted January 30, 2013 You are returning the result of the conversion from the function, with this line: return $kms; This means that whenever you call the function miles2kms (), it will return a value which you need to save/show. The simplest way to get it to show, though only good for really small script like this, is to just echo it out directly. In other words add echo in front of the function call. That said, you haven't actually called the function in your code. Just defined it. Which means it won't do anything. In light of that, I recommend that you start here, and follow the breadcrumbs onwards. For this particular issue, you want to give special notice to the user defined functions page. As it will explain how they work. PS: Please use the [code][/code] tags around your code, as it helps make both your post and your code a lot easier to read. Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/273824-first-php-code-please-help-me/#findComment-1409134 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.