Abdulelah Al Jeffery Abdulelah Al Jeffery - 4 months ago 21
PHP Question

Retrieve multiple checkboxes stored as an array

I am working on a form that contains multiple checkboxes (each with its own value). The last checkbox is marked "Other" and, when it is checked, a text input should appear to let the user write his/her own value.

<input name="pVital[]" type="checkbox" id="pVital[]" value="I &amp; O" />I &amp; O<br/>
<input name="pVital[]" type="checkbox" id="pVital[]" value="Daily Weight" />Daily Weight<br/>
<input name="pVital[]" type="checkbox" id="pVital[]" value="Foley Catheter" />Foley Catheter<br/>
<input name="pVital[]" type="checkbox" id="pVital[]" onClick="showHide(whatever);" value="" />Other<br/>
<input name="pVital[]" type="text" id="whatever" style="visibility: hidden;" />


I insert all these values into the same field in my database, as an array of strings, using php's
implode
function:

if ((isset($_POST['pVital']))){
array_walk($spVital, 'GetSQLValueString');
$spVital = implode(',',$_POST['pVital']);
}

$insertSQL = sprintf("INSERT INTO admissionorder (VitalSigns) VALUES (%s)",
GetSQLValueString($spVital, "text"));

mysql_select_db($database_PPS, $PPS);
$Result1 = mysql_query($insertSQL, $PPS) or die(mysql_error());


This is working fine for insertion, but I encounter a problem in retrieving these checkboxes... with the "other" text input if appropriate.

Answer

This did it for me:

<?php 
    $pvitals = explode('|', $row_pInfoRecordset['VitalSigns']);
?>

then:

<input name="pVital[]" type="checkbox" id="pVital[]" value="I &amp; O" checked="<?php if (in_array('I &amp; O', $pvitals)) echo "checked"; else echo "unchecked"; ?>" />I &amp; O<br/>
  <input <?php if (in_array('Daily Weight', $pvitals)) echo "checked"; else echo "unchecked";  ?> name="pVital[]" type="checkbox" id="pVital[]" value="Daily Weight" />Daily Weight<br/>
  <input <?php if (in_array('Foley Catheter', $pvitals)) echo "checked"; else echo "unchecked"; ?> name="pVital[]" type="checkbox" id="pVital[]" value="Foley Catheter" />Foley Catheter<br/>
  <input <?php if (in_array('other', $pvitals)) echo "checked"; else echo "unchecked"; ?> name="pVital[]" type="checkbox" id="other" onClick="showHide(whatever);" value="other" />Other<br/>
    <input name="pVital[]" type="text" id="whatever" <?php if (in_array('other', $pvitals)) { $vis = 'style="visibility: visible;"'; echo $vis; ?> <?php } else { ?> style="visibility:hidden" <?php } ?>  value="<?php if (in_array('other', $pvitals)) echo end($pvitals); ?>">