0

Right now i changed from options table to my own table so things are getting difficult

i have a checkbox its name is selection in table, so here is what i tried

<input type="checkbox" name="selection" value="1"<?php checked("1",$item['selection']);?> />
<input type="checkbox" name="selection" value="2"<?php checked("2",$item['selection']);?> />
<input type="checkbox" name="selection" value="3"<?php checked("3",$item['selection']);?> />

This is not saving any value , Then i tried as array in below

<input type="checkbox" name="selection[]" value="1"<?php checked("1",$item['selection']);?> />
<input type="checkbox" name="selection[]" value="2"<?php checked("2",$item['selection']);?> />
<input type="checkbox" name="selection[]" value="3"<?php checked("3",$item['selection']);?> />

It is throwing warning Warning: mysql_real_escape_string() expects parameter 1 to be string, array given

How to store multiple values with the same name in checkbox when using my table ?

Any help help would be greatful.

1

The WordPress function checked() just compares two given values and - if the comparison is true - adds the checked attribute to a radio button or checkbox. The second parameter is default true so you can use the PHP function in_array() if you have to check if a given value is in an array like this

<input type="checkbox" name="selection[]" value="1" <?php checked( in_array( '1', $item['selection'] ) ); ?> />
<input type="checkbox" name="selection[]" value="2" <?php checked( in_array( '2', $item['selection'] ) ); ?> />
<input type="checkbox" name="selection[]" value="3" <?php checked( in_array( '3', $item['selection'] ) ); ?> />

I assume that you saved your data serialized and that you unserialize them before you use them like in the example.

When you submit the form you can get and serialize the value of the field for saving it into the db like this

$str = maybe_serialize( $_POST['selection'] );

When you then get it from the database you should unserialize the value

$item['selection'] = maybe_unserialize( $str );

This is important because just in this way you can restore the array.

  • Thanks for your answer +1 for in_array. am not sure about data serialize is maybe_serialize fine for that? – sun Oct 31 '13 at 10:33
  • Yes, it is perfect for that. – realloc Oct 31 '13 at 10:35
  • Sorry i couldn't figure out that. I tried like <?php $serialized_sel = maybe_serialize('selection'); ?> and used this in the name field like name="<?php echo $serialized_sel; "?> any help please – sun Oct 31 '13 at 10:47
  • Warning: in_array() expects parameter 2 to be array, string given – sun Oct 31 '13 at 10:56
  • 1
    OK I will add an example what I mend with the serialization-part. – realloc Oct 31 '13 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.