Related
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
}
?>
How to read if a checkbox is checked in PHP?
If your HTML page looks like this:
<input type="checkbox" name="test" value="value1">
After submitting the form you can check it with:
isset($_POST['test'])
or
if ($_POST['test'] == 'value1') ...
Zend Framework use a nice hack on checkboxes, which you can also do yourself:
Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of "0". Then if your checkbox as the value "1", you'll always get the '0' or '1' value in the resulting GET or POST
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
When using checkboxes as an array:
<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">
You should use in_array():
if(in_array('Orange', $_POST['food'])){
echo 'Orange was checked!';
}
Remember to check the array is set first, such as:
if(isset($_POST['food']) && in_array(...
Let your html for your checkbox will be like
<input type="checkbox" name="check1">
Then after submitting your form you need to check like
if (isset($_POST['check1'])) {
// Checkbox is selected
} else {
// Alternate code
}
Assuming that check1 should be your checkbox name.And if your form submitting method is GET then you need to check with $_GET variables like
if (isset($_GET['check1'])) {
// Checkbox is selected
}
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.
HTML Code: (for Add Page)
<input name="status" type="checkbox" value="1" checked>
Hint: remove checked if you want to show it as unchecked by default
HTML Code: (for Edit Page)
<input name="status" type="checkbox" value="1"
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>
PHP Code: (use for Add/Edit pages)
$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}
Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.
To check if a checkbox is checked use empty()
When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.
Check if checkbox is checked with empty as followed:
//Check if checkbox is checked
if(!empty($_POST['checkbox'])){
#Checkbox selected code
} else {
#Checkbox not selected code
}
You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.
i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:
if(isset($_POST['test']) {
// The checkbox was enabled...
}
You can do it with the short if:
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
or with the new PHP7 Null coalescing operator
$check_value = $_POST['my_checkbox_name'] ?? 0;
Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set
Example:
if(isset($_POST["testvariabel"]))
{
echo "testvariabel has been set!";
}
Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:
//EMPTY ALL VALUES TO 0
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
if(!empty($_POST['check_menus'])) {
foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
$queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
} catch(PDOException $e) {
$msg = 'Error: ' . $e->getMessage();}
}
}
<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />
....
The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.
Example is PHP but applies for everything.
Have fun :)
$is_checked = isset($_POST['your_checkbox_name']) &&
$_POST['your_checkbox_name'] == 'on';
Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.
A minimalistic boolean check with switch position retaining
<?php
$checked = ($_POST['foo'] == ' checked');
?>
<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>
<?php
if (isset($_POST['add'])) {
$nama = $_POST['name'];
$subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";
echo "Name: {$nama} <br />";
echo "Subscribe: {$subscribe}";
echo "<hr />";
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="text" name="name" /> <br />
<input type="checkbox" name="subscribe" value="news" /> News <br />
<input type="submit" name="add" value="Save" />
</form>
<form>
<input type="check" id=chk1 value="1">
<input type="check" id=chk2 value="1">
<input type="check" id=chk3 value="1">
</form>
when you check on chk2 you can see values as:
<?php
foreach($_POST as $key=>$value)
{
if(isset($key))
$$key=strip_tags($value);
}
insert into table (chk1,chk2,chk3) values ('','1','');
?>
in BS3 you can put
<?php
$checked="hola";
$exenta = $datosOrdenCompra[0]['exenta'];
var_dump($datosOrdenCompra[0]['exenta']);
if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){
$checked="on";
}else{
$checked="off";
}
?>
<input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>
Please Note the usage of isset($datosOrdenCompra[0]['exenta'])
Wordpress have the checked() function.
Reference: https://developer.wordpress.org/reference/functions/checked/
checked( mixed $checked, mixed $current = true, bool $echo = true )
Description
Compares the first two arguments and if identical marks as checked
Parameters
$checked
(mixed) (Required) One of the values to compare
$current
(mixed) (Optional) (true) The other value to compare if not just true
Default value: true
$echo
(bool) (Optional) Whether to echo or just return the string
Default value: true
Return #Return
(string) html attribute or empty string
i have fixed it into a PHP form with a checkbox
$categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] );
foreach ($categories as $categorie) {
echo "<input type="checkbox" value="$categorie->term_taxonomy_id" name="catselected[]"> $categorie->slug";
}
This way i add it to the Woocommerce tabel.
wp_set_post_terms( $product_id, $_POST['catselected'], 'product_cat' );
filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)
<?php
if(isset($_POST['nameCheckbox'])){
$_SESSION['fr_nameCheckbox'] = true;
}
?>
<input type="checkbox" name="nameCheckbox"
<?php
if(isset($_SESSION['fr_nameCheckbox'])){
echo 'checked';
unset($_SESSION['fr_nameCheckbox']);
}
?>
you should give name to your input .
then which box is clicked you will receive 'on' in your choose method
Array
(
[shch] => on
[foch] => on
[ins_id] => #
[ins_start] => شروع گفتگو
[ins_time] => ما معمولاً در چند دقیقه پاسخ میدهیم
[ins_sound] => https://.../media/sounds/ding-sound-effect_2.mp3
[ins_message] => سلام % به کمک نیاز دارید؟
[clickgen] =>
)
i have two checked box in my form name with 'shch' and 'foch'
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!
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";
How to read if a checkbox is checked in PHP?
If your HTML page looks like this:
<input type="checkbox" name="test" value="value1">
After submitting the form you can check it with:
isset($_POST['test'])
or
if ($_POST['test'] == 'value1') ...
Zend Framework use a nice hack on checkboxes, which you can also do yourself:
Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of "0". Then if your checkbox as the value "1", you'll always get the '0' or '1' value in the resulting GET or POST
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
When using checkboxes as an array:
<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">
You should use in_array():
if(in_array('Orange', $_POST['food'])){
echo 'Orange was checked!';
}
Remember to check the array is set first, such as:
if(isset($_POST['food']) && in_array(...
Let your html for your checkbox will be like
<input type="checkbox" name="check1">
Then after submitting your form you need to check like
if (isset($_POST['check1'])) {
// Checkbox is selected
} else {
// Alternate code
}
Assuming that check1 should be your checkbox name.And if your form submitting method is GET then you need to check with $_GET variables like
if (isset($_GET['check1'])) {
// Checkbox is selected
}
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.
HTML Code: (for Add Page)
<input name="status" type="checkbox" value="1" checked>
Hint: remove checked if you want to show it as unchecked by default
HTML Code: (for Edit Page)
<input name="status" type="checkbox" value="1"
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>
PHP Code: (use for Add/Edit pages)
$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}
Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.
To check if a checkbox is checked use empty()
When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.
Check if checkbox is checked with empty as followed:
//Check if checkbox is checked
if(!empty($_POST['checkbox'])){
#Checkbox selected code
} else {
#Checkbox not selected code
}
You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.
i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:
if(isset($_POST['test']) {
// The checkbox was enabled...
}
You can do it with the short if:
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
or with the new PHP7 Null coalescing operator
$check_value = $_POST['my_checkbox_name'] ?? 0;
Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set
Example:
if(isset($_POST["testvariabel"]))
{
echo "testvariabel has been set!";
}
Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:
//EMPTY ALL VALUES TO 0
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
if(!empty($_POST['check_menus'])) {
foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
$queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
} catch(PDOException $e) {
$msg = 'Error: ' . $e->getMessage();}
}
}
<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />
....
The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.
Example is PHP but applies for everything.
Have fun :)
$is_checked = isset($_POST['your_checkbox_name']) &&
$_POST['your_checkbox_name'] == 'on';
Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.
A minimalistic boolean check with switch position retaining
<?php
$checked = ($_POST['foo'] == ' checked');
?>
<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>
<?php
if (isset($_POST['add'])) {
$nama = $_POST['name'];
$subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";
echo "Name: {$nama} <br />";
echo "Subscribe: {$subscribe}";
echo "<hr />";
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="text" name="name" /> <br />
<input type="checkbox" name="subscribe" value="news" /> News <br />
<input type="submit" name="add" value="Save" />
</form>
<form>
<input type="check" id=chk1 value="1">
<input type="check" id=chk2 value="1">
<input type="check" id=chk3 value="1">
</form>
when you check on chk2 you can see values as:
<?php
foreach($_POST as $key=>$value)
{
if(isset($key))
$$key=strip_tags($value);
}
insert into table (chk1,chk2,chk3) values ('','1','');
?>
in BS3 you can put
<?php
$checked="hola";
$exenta = $datosOrdenCompra[0]['exenta'];
var_dump($datosOrdenCompra[0]['exenta']);
if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){
$checked="on";
}else{
$checked="off";
}
?>
<input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>
Please Note the usage of isset($datosOrdenCompra[0]['exenta'])
Wordpress have the checked() function.
Reference: https://developer.wordpress.org/reference/functions/checked/
checked( mixed $checked, mixed $current = true, bool $echo = true )
Description
Compares the first two arguments and if identical marks as checked
Parameters
$checked
(mixed) (Required) One of the values to compare
$current
(mixed) (Optional) (true) The other value to compare if not just true
Default value: true
$echo
(bool) (Optional) Whether to echo or just return the string
Default value: true
Return #Return
(string) html attribute or empty string
i have fixed it into a PHP form with a checkbox
$categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] );
foreach ($categories as $categorie) {
echo "<input type="checkbox" value="$categorie->term_taxonomy_id" name="catselected[]"> $categorie->slug";
}
This way i add it to the Woocommerce tabel.
wp_set_post_terms( $product_id, $_POST['catselected'], 'product_cat' );
filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)
<?php
if(isset($_POST['nameCheckbox'])){
$_SESSION['fr_nameCheckbox'] = true;
}
?>
<input type="checkbox" name="nameCheckbox"
<?php
if(isset($_SESSION['fr_nameCheckbox'])){
echo 'checked';
unset($_SESSION['fr_nameCheckbox']);
}
?>
you should give name to your input .
then which box is clicked you will receive 'on' in your choose method
Array
(
[shch] => on
[foch] => on
[ins_id] => #
[ins_start] => شروع گفتگو
[ins_time] => ما معمولاً در چند دقیقه پاسخ میدهیم
[ins_sound] => https://.../media/sounds/ding-sound-effect_2.mp3
[ins_message] => سلام % به کمک نیاز دارید؟
[clickgen] =>
)
i have two checked box in my form name with 'shch' and 'foch'