问题
I have a single checkbox in a form which I want to assign values to for both checked and unchecked states. The values are saved in a MySQL database. This is my php to retrieve the values.
<?php
// Value = 10.00
// This should be the checked value (initial state)
function getDel1()
{
global $con;
$get_del1 = "select * from delivery";
$run_del1 = mysqli_query($con, $get_del1);
while($row_del1=mysqli_fetch_array($run_del1)){
$leeds = $row_del1['delivery_leeds'];
echo "$leeds";
}
}
?>
<?php
// Value = 20.00
// This should be the unchecked value (user interaction)
function getDel2()
{
global $con;
$get_del2 = "select * from delivery";
$run_del2 = mysqli_query($con, $get_del2);
while($row_del2=mysqli_fetch_array($run_del2)){
$leeds = $row_del2['delivery_other'];
echo "$other";
}
}
?>
I can display the values independently by calling either function in a div which is adjacent to the form checkbox but I don't know how to assign those values to the form checkbox and then automatically update the div depending on the user interaction. Any suggestions?
回答1:
A ternary operator can take care of both assigned values and unassigned default values.
Example:
$checkbox = isset($_POST['checkbox']) ? $_POST['checkbox'] : "Default value if unchecked";
This is equivalent to doing: (which you can also use).
if (isset($_POST['checkbox'])){
$checkbox=$_POST['checkbox'];
// do something, as in run a function
}
else{
$checkbox="Default value if unchecked";
// do something else, as in run a different function
}
You can also remove the default text and do "" in the ternary to leave it empty.
Reference:
- http://php.net/manual/en/language.operators.comparison.php
Footnotes:
Make sure the checkbox holds the name attribute.
I.e. name="checkbox" as an example.
and your form has a POST method. Use the appropriate method accordingly.
- So in your case and as seen in comments from code you left there, change
checkboxin the arrays todeliver.
Your checkbox value can also use the following, as a ternary example:
<input type="checkbox" name="deliver" value="<?php echo isset($_POST['deliver']) ? $_POST['deliver'] : "Default value if unchecked"; ?>" />
来源:https://stackoverflow.com/questions/33281558/can-i-assign-values-to-a-checkbox-for-checked-and-unchecked-states