Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

php - Can I assign values to a checkbox for checked and unchecked states?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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 checkbox in the arrays to deliver.

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"; ?>" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...