Hello all,
I am trying to learn OOP in PHP so please forgive my ignorance. I seem to be having difficulty inserting data into my database from checkbox items. My database has a column for each each fruit. I would like for each column to be populated with either a one(1) for checked or a zero(0) for not checked. Currently, my attempts have failed. I can either get all checkboxes to insert all zeros or I can get the first column to insert a one(1) while the others as zeros. Is there anybody here that can help me figure out what I am doing wrong and help me to re-work my code so I can get this to work? If anybody can help me using OOP methods that would be fantastic. Thank you all in advance.
$preffruit->create_preffruit(array(
'fruit_apple' => escape(Input::get(['fruit_selection'][0]) ? 1 : 0),
'fruit_orange' => escape(Input::get(['fruit_selection'][1]) ? 1 : 0),
'fruit_banana' => escape(Input::get(['fruit_selection'][2]) ? 1 : 0),
'fruit_pear' => escape(Input::get(['fruit_selection'][3]) ? 1 : 0),
'fruit_kiwi' => escape(Input::get(['fruit_selection'][4]) ? 1 : 0)
));
<input type="checkbox" name="fruit_selection[]" value="fruit_apple">
<input type="checkbox" name="fruit_selection[]" value="fruit_orange">
<input type="checkbox" name="fruit_selection[]" value="fruit_banana">
<input type="checkbox" name="fruit_selection[]" value="fruit_pear">
<input type="checkbox" name="fruit_selection[]" value="fruit_kiwi">
public function insert_preffruit($table, $fields = array()) {
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field) {
$values .= '?';
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO preffruit (`user_id`, `" . implode('`, `', $keys) . "`) VALUES (LAST_INSERT_ID(), {$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}