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

Categories

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

mysql - Updating Already Checked Checkboxes in PHP

let's say I have a list of checkboxes that the user selects.

<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...

The user selected Water and it is added to the database. Now the user wants to update the list:

<input type="checkbox" name="utility[]" id="utility[]" value="Water" checked="checked"/>Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...

How can I check that the utility has already been checked in PHP?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

What I've done in the past, to save having hundreds of lines of bloat is this...

First compile all the html in a variable, without any "checked" instances.

$boxes = '';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />';

Now I loop over your array of fields to check. I've provided a sample array here too.

$already_checked = array('Water', 'Electricity');

foreach( $already_checked as $ac ) {
    $find = 'value="' . $ac . '"';
    $replace = $find . ' checked="checked"';
    $boxes = str_replace($find, $replace, $boxes);
}

echo $boxes;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...