Hi All,
I am using Moodle 1.9.3.
In course, I have added one field
$select = &$mform->addElement('select', 'colors', get_string('colors'), array(1 => 'red', 2 => 'blue', 3 => 'green'));
$select->setMultiple(true);
But in the database, the value stores as 'Array' .
How do I store the keys of the array in the database?
Please help me
In reply to Barbara Joe
Re: urgent help !! saving multiple selects value in database
Dear Barbara joe,
Please help me understand what you are trying to do,
you mean the database stores the term 'Array' instead of array of values ?
and secondly why would you want to store the keys of array in database instead of values ?
Please help me understand what you are trying to do,
you mean the database stores the term 'Array' instead of array of values ?
and secondly why would you want to store the keys of array in database instead of values ?
In reply to Ravishankar Somasundaram
Re: urgent help !! saving multiple selects value in database
by Mark Johnson -
It makes sense to store the key as an ID for the option, that way it allows the options to be changed or translated without having to change the data being handled.
The issue here is that because you can select more than one option on the form, these are passed as an array of the selected options (even if it's only 1 option), so you need to loop through the array and store each one in the database.
e.g. (not sure if this is the exact code off the top of my head)
$data = $form->getData();
foreach($data->colors as $color) {
insert_record('tablename', 'fieldname', $color);
}
The issue here is that because you can select more than one option on the form, these are passed as an array of the selected options (even if it's only 1 option), so you need to loop through the array and store each one in the database.
e.g. (not sure if this is the exact code off the top of my head)
$data = $form->getData();
foreach($data->colors as $color) {
insert_record('tablename', 'fieldname', $color);
}
In reply to Ravishankar Somasundaram
Re: urgent help !! saving multiple selects value in database
by chhavi garg -
hey pls tell me how to store array values in db.
when i write
$data->loc=FORMAT_HTML
it stores array index but i want to store array values.
cn u plz tell??
In reply to Barbara Joe
Re: urgent help !! saving multiple selects value in database
by Matt Gibson -
You need a DB table ready to store these values, one per row. You have the option of serialising the data using
$datatostore = serialize($array);
but this is not best practice as you can't later do SQL selects for e.g. all users who chose option 1. Better is this:
$data = $mform->get_data();
$array = $data['colors'];
foreach ($colors as $key => $color) {
$record = new stdClass();
$record->userid = $data['userid'];
$record->color = $color; // or $key
$DB->insert_record('nameoftable', $record);
}
Which will store the values one by one.