I am trying to convert deg -> c and c -> deg using php. The objective is to use functions containing the formulas and then having a form with radio buttons and a text box. The user should be able to enter the degree in the text box, click the radio button of their choice (F or C) and then submit the form to receive their conversion. I have seen similar posts but the methodology is not specific to the issue I am having.
I have updated my code but am now getting the "White page of death"
Can anyone see an error that I cannot see? Thank you!
HTML
<h1>Temperature Conversion</h1>
<form action='lab_exercise_6.php' method ='POST'>
<p>Enter a temp to be converted and then choose the conversion type below.</p>
<input type ='text' maxlength='3' name ='calculate'/>
<p>Farenheit
<input type="radio" name='convertTo' value="f" />
</p>
<p>Celsius
<input type="radio" name='convertTo' value="c" />
</p>
<input type='submit' value='Convert Temperature' name='convertTo'/>
PHP
<?php
//function 1
function FtoC($deg_f) {
return ($deg_f - 32) * 5 / 9;
}
//function 2
function CtoF($deg_c){
return($deg_c + 32) * 9/5;
}
if( isset($_POST['convertTo']) && $_POST['convertTo'] ==="c" ){
$farenheit = FtoC($deg_f);
print('This temperature in FARENHEIT is equal to ' . $celsius . ' degrees celsius! </br>');
}else if(isset($_POST['convertTo'])&& $_POST['convertTo']==='f'){
$celsius = CtoF($deg_c);
print('This temperature in CELSIUS is equal to ' . $farenheit . ' degrees farenheit! </br>');
}
?>
it's this part that makes it behave unexpected:
$farenheit = FtoC($deg_f);
// And then a few lines lower:
if(isset($farenheit)){ /* ... */}
You set it to a value right there, so it will always try to calculate an outcome.
With a small tweak you will use the radiobutton more as it is intended:
<input type="radio" name="convertTo" value="f" />
<input type="radio" name="convertTo" value="c" />
The value in PHP will now always have the same name, you can now just check it's value:
if( isset($_POST['convertTo']) && $_POST['convertTo']==="c" ){
$farenheit = FtoC($deg_f);
print('This temperature in FARENHEIT is equal to ' . $celsius . ' degrees celsius! </br>');
}
You haven't added values to the radio boxes.
Then change your radio name same as the other so for example
<p>Farenheit
<input type = 'radio' name ='temp_type' value='f'/>
</p>
<p>Celsius
<input type = 'radio' name ='temp_type' value='c'/>
</p>
Now you can access those with PHP.
if($_POST['temp_type'] && ($_POST['calculate']){
$temp2calculate = $_POST['calculate'];
$temp_type = $_POST['temp_type'];
}
You have to give same name for the radio buttons
<p>Farenheit
<input type = 'radio' value ='farenheit' name='units'/>
</p>
<p>Celsius
<input type = 'radio' value ='celsius' name='units'/>
</p>
Check whether which radio button is selected:
<?php
$units = $_POST['units'];
if($units == "fahrenheit"){
//call function to convert to fahrenheit
}
else{
//call function to convert to celsius
}
?>
Related
Can anyone help me with getting PHP to reference the value or id attribute in form handling. I can only see how to reference the name using $_POST, how can this work with radio input type when the name is not unique?
Thanks in advance for any advice.
input type="radio" name="fuel" value="Unleaded" id="fuel_0"
/>Unleaded</label><br />
<label>
<input type="radio" name="fuel" value="Diesl" id="fuel_1"
/>Diesel</label><br />
<label>
<input type="radio" name="fuel" value="Super Unleaded" id="fuel_2"
/>Super Unleaded</label><br />
<label>
<input type="radio" name="fuel" value="Premium Diesel" id="fuel_3"
/>Premium Diesel</label></p>
<p>
<input type="submit" name="Submit" id="Submit" value="Calculate" /><br />
You do reference the name using $_POST. The name is still unique even if the radio button name fuel shows 4 times. It is unique for the whole group and only one will be selected so you only have one value.
$radioValue = $_POST["fuel"];
Radio buttons work by giving all of inputs in a particular group the same name. However, when the form is submitted, only the value from the selected radio button is sent to the server. PHP will only end up seeing the one value.
I guess I should have rephrased the question to ask how to choose a different function depending on which option was chosen as you can't differentiate by using the name if they are all the same. I've got this working using the below code. I didn't realise before today that you could just refer to the value. Thanks to those of you who answered my earlier question.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{if(isset($_REQUEST['amount'])&&is_numeric($_REQUEST['amount'])){
$litres=$_REQUEST['amount'];}
else {echo "please enter a valid amount";$litres=0;}
$choice = $_POST ['fuel'];
if ($choice == "Unleaded"){echo "litres=amount= " . $litres . " final cost
is " . unleaded($litres) ;}
if ($choice == "Diesl"){echo "litres=amount= " . $litres . " final cost is
" . diesel($litres) ;}
if ($choice == "Super Unleaded"){echo "litres=amount= " . $litres . " final
cost is " . Superunleaded($litres) ;}
if ($choice == "Premium Diesel"){echo "litres=amount= " . $litres . " final
cost is " . premiemdiesel ($litres) ;}
}
I'm on the learning mode.
<?php
if (!empty($_POST['fifty']) || !empty($_POST['sixty'])) {
$fifty = (isset($_POST['fifty'])) ? (int)$_POST['fifty'] : 0;
$sixty = (isset($_POST['sixty'])) ? (int)$_POST['sixty'] : 0;
echo $fifty + $sixty;
} else {
echo "No selection selected";
}
?>
<form method="post">
<input type="radio" name="fifty" value="50"/>
<input type="radio" name="sixty" value="60"/>
<input type="submit" name="submit" value="Submit"/>
</form>
This only works when I select both radio buttons. How do I make this work when I just select 1 radio button instead of 2?
And is the way I coded the PHP the good way to write it? I get an idea that I do double work with checking :P
And how do I do it with three radio options? Can you give me a example with a third radio option called seventy with value 70?
My idea is to make it + count the values if 1 and 3 are slected it must to 50+70
if 2 and 3 are selected it must do 60 + 70, etc, etc.
Use ||for OR, && for AND
if(!empty($_POST['fifty']) || !empty($_POST['sixty'])){
$fifty = (isset($_POST['fifty']))? (int)$_POST['fifty'] : 0;
$sixty = (isset($_POST['sixty']))? (int)$_POST['sixty'] : 0;
echo $fifty + $sixty;
} else {
echo "No selection selected";
}
A few things to change.
The <input /> tags.
<input type="radio" name="fifty" value="50" />
<input type="radio" name="sixty" value="60" />
The logic you used (which you have corrected).
if (!empty($_POST['fifty']) || !empty($_POST['sixty']))
Remove unnecessary code:
$submit = $_POST['submit'];
Using WordPress, so PHP, HTML, CSS, JavaScript what is the best method of populating the results of a form upon submission? I could have a form with ddl, radio buttons, etc.
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
What is the best way of populating the results i.e. "67% of users are Female" and "30% ride bikes" on the same page once the submit button is triggered?
Try something along these lines:
script.php
----------
<html>
<body>
<form method=post action=script.php>
your form here...
</form>
<? if($_SERVER["CONTENT_LENGTH"]>0) {
//form was submitted to script, so process form inputs here and display results...
}
?>
</body>
</html>
<form action="phpfile.php" method="Post">
...form here
</form>
phpfile.php:
<?php
if(isset($_POST['sex'])){
$sex = $_POST['sex'];
}//etc..
//To show the result, simply echo it:
echo $sex;
You'll need some sort of storage system to be able to calculate the amount of each.
So what you would need to do is write a simple query where the value of the field is male or female. Then you can easily calculate it.
What you will need to do is add the form results to the database, then find the total number of results for both categories, then calculate the percent female and the percent bike.
The form page:
<html>
<?php
if(isset($_GET['status']) && $_GET['status'] == "values") {
//connect to DB and select table
$male = count( mysql_query("SELECT gender FROM Table WHERE gender='male'"));
$female = count (mysql_query("SELECT gender FROM Table WHERE gender='female'"));
$car = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='car'"));
$bike = count (mysql_query("SELECT vehicle FROM Table WEHRE vehicle='bike'"));
$totalResults = $male + $female;
$totalVehicles = $car + $bike;
$percentFemale = 100 * ($female / $totalResults);
$percentFemale = number_format($percentFemale, 0);
$percentBike = 100 * ($bike / $totalVehicals);
$percentBike = number_format($totalBike, 0);
echo "<p>" . $percentFemale . "% of users are female. </p>";
echo "<p>" . $percentBike . "% of users use bikes. </p>";
} else { ?>
<form action="formProcessor.php" method="POST"><!-- You could also use GET -->
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<input type="submit" value="Submit">
</form>
<?php } ?>
</html>
The formProcessor.php Page:
<?php
if(isset($_POST["sex"]) && isset($_POST['vehicle'])) {
//Connect to MySQL DB and select table here
$sex = $_POST['sex'];
$vehicle = $_POST['vehicle'];
mysql_query("INSERT INTO Table(sex, vehicle) VALUES($sex, $vehicle)"); //You may also want to add an id column, but...
//Close mysql connection
header("Location: /form.php?status=values");
die();
} else {
die("There was an error in your submission.");
}
?>
I think this answers your question, you've got a way to find the percent of female users and users on bikes. If you need that to be dynamic and show only the greater amount (or show both or something) just add a comment. This also assumes you are not using PDO, if you are, I can adjust the code. I just wrote the code, so I don't know for sure if it works, but here you go!
Basically what I want my program to do is to ask the user how many numbers they want to enter. Once the value is submitted, the program will take the value and create this amount of textboxes. Each textbox will take a number and once submitted, it should take all the numbers (excluding the initial text box) and store it into an array or something so the mean can be calculated.
I've been able to get as far as creating x amount of textboxes but cannot find a way to submit these values.
<html>
<body>
<form action="means.php" method = "get">
Enter sample size: <input type = "number" name = "size" <br>
<input type = "submit">
<?php
if ( isset($_GET["size"] ) )
{
$size = $_GET["size"];
$count = 1;
while ($count <= $size)
{
echo '<br><input type=\"text\" name=\"textbox".$count."\" />';
$count++;
}
}
?>
</form>
</html>
</body>
I assume the problem is that the textboxes created are being echoed so the name "textbox.$count." cannot be used to obtain the numbers?
Any help would be greatly appreciated. Thanks in advance!
Just use PHP's array notation for form field names:
<input type="text" name="textbox[]" />
^^---force array mode
which will produce an array in $_POST['textbox'], one element for each textbox which was submitted with the textbox[] name.
e.g:
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
produces
$_POST = array(
'textbox' => array )
0 => 1,
1 => 'foo',
2 = > 'banana'
)
)
Your problem is that you're using single-quoted strings ('), meaning that
$var = 'foo';
echo '$var' // outputs $, v, a, r
echo "$var" // outputs f, o ,o
I'm trying to figure out how to make the logic in the following form work. Basically if either of the first two radio buttons is checked, make the hidden input named categories have a value of vegetables. Else, make the hidden input named categories have a value of fruits.
I'm not sure if this should be done with PHP or JavaScript, but if it is done with PHP I think the form would have to be submitted to itself to be pre-processed and then the collected, pre-processed information would be sent to external_form_processor.php. If this is how you do it, what would be the PHP code that I need to use to make it work?
<?php
if($_POST["food"]=="carrots" || $_POST["food"]=="peas") {
$category = "vegetables";
} else {
$category = "fruits";
}
?>
<form name="food_form" method="post" action="external_form_processor.php" >
<fieldset>
<input type="radio" id="carrots" name="food" value="carrots" />
<input type="radio" id="peas" name="food" value="peas" />
<input type="radio" id="orange" name="food" value="orange" />
<input type="radio" id="apple" name="food" value="apple" />
<input type="radio" id="cherry" name="food" value="cherry" />
</fieldset>
<input type="hidden" name="categories" value="<?php $category ?>" />
</form>
If using jQuery would be easier, how could I call the variable as the value of the hidden input if I use the following in the head of the page?
$(function(){
$('input[name=food]').click(function(){
var selected_id = $('input[name=food]:checked').attr('id');
if (selected_id == 'carrots' || selected_id == 'peas') {
var category = "vegetables";
} else {
var category = "fruits";
}
});
});
Any help with this would be greatly appreciated. Thanks!
I think jQuery would work perfect for you, you just need to pass the category value to the input field:
$(function(){
$('input[name=food]').click(function(){
var selected_id = $('input[name=food]:checked').attr('id');
if (selected_id == 'carrots' || selected_id == 'peas') {
var category = "vegetables";
} else {
var category = "fruits";
}
$('input[name=categories]').val(category);
});
});
I would set the category in PHP when the form is submitted.
//validate inputs... always
$food = "";
if(isset($_GET['food'])){
$food = preg_replace("/[^a-zA-Z]+/", "", $_GET['food']);
}
$category = ($food=="peas"||$food=="carrots")?"vegetables":"fruits";