Jump to content

first php code - please help me


benjahnee

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/273824-first-php-code-please-help-me/
Share on other sites

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>

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.