How to insert data to database from multiple select dropdown in codeigniter? - php

I have drop down which is look like the following
<select class="selectpicker form-control" multiple name="category[]">
<option value="1" id="MENTAL HEALTH">MENTAL HEALTH</option>
<option value="2" id="SUICIDE SUPPORT">SUICIDE SUPPORT</option>
<option value="3" id="HEALTH">HEALTH</option>
<option value="4" id="SUPPORT">SUPPORT</option>
</select>
In my controller I have the following code to get that data from the dropdown
public function save()
{
$ctgry= ($this->input->post('category'));
$orgName= ($this->input->post('InputName'));
$streetNo= ($this->input->post('StreetNo'));
$streetName= ($this->input->post('StreetName'));
$suburb= ($this->input->post('Suburb'));
$state= ($this->input->post('state'));
$postCode= ($this->input->post('PostCode'));
$count = count($ctgry);
$supprtGroup = array(
'name' => $orgName,
'street_no' => $streetNo,
'street' => $streetName,
'suburb' => $suburb,
'state' => $state,
'pc' => $postCode
);
$supportgroup_id = $this->Home_Model->addSupportGroup($supprtGroup);
$j = 0;
i = 0;
$sc_id = 0
echo 'aa';//just for error checking purpose
if ($count > 1)
{
echo ' aa1';//just for error checking purpose
while ($i > $count)
{
echo ' aa2';//just for error checking purpose
$support_category = array(
'supportgroup_id' => $supportgroup_id,
'category_id' => $ctgry[$j]
);
$sc_id = $this->Home_Model->addSupportrCategory($support_category);
$i++;
echo $sc_id;//just for error checking purpose
}
}
else
{
echo ' aa3';//just for error checking purpose
$support_category = array(
'supportgroup_id' => $supportgroup_id,
'category_id' => $ctgry[$j]
);
$sc_id = $this->Home_Model->addSupportrCategory($support_category);
echo $sc_id;//just for error checking purpose
}
echo'bb';//just for error checking purpose
}
The following is my model class
function addSupportGroup($supprtGroup=NULL)
{
$this->db->insert('support_group', $supprtGroup);
return $this->db->insert_id();
}
function addSupportrCategory($support_category=NULL)
{
$this->db->insert('support_category', $support_category);
return $this->db->insert_id();
}
When select multiple values from dropdown the out put as follows
aa aa1bb
Could anyone give me an answer why this is happening, if it is a single value
selected from the dropdown its saving to the DB fine I search every similar
posts but couldn't find the answer.

I can't see where $count is defined in your question so I don't know what it's value is meant to be, however, if you are getting "aa1" as output you are saying that it's bigger than 1.
With your while() you're saying that $i must be bigger than $count but $i equals 0 so therefore the while loop won't start.
If you are just wanting to loop through the categories it would be easier to just:
$supportgroup_id = $this->Home_Model->addSupportGroup($supprtGroup);
foreach ($ctgry as $cat) {
$insert = array(
'supportgroup_id' => $supportgroup_id,
'category_id' => $cat
);
$sc_id = $this->Home_Model->addSupportrCategory($support_category);
}
This will work because the dropdown will always be picked up as an array.
You should also look at adding some validation to this!
Hope this helps!

Related

drop down value not being submitted to post array

Currently working with a php project in which I connect to a database in phpmyadmin. I'm currently implementing my one to many relationship and on one of my forms there is a drop down list with the list of categorys(foreign key) that a product in my database can have, however when I check the post array, and the array that contains all the values for the insert query everything is there except the foreign key.
Drop down list and array of values:
<select name="Category_ID">
<?php
foreach ($category as $cat) {
echo '<option value="' . $cat['ID'] . '">' . $cat['ID'] . '</option>';
}
?>
</select>
Array (
[authorName] => Hiroshi Sakurazaka
[bookName] => All You Need Is Kill
[costPrice] => 59
[sellPrice] => 99
[productCatID] => )
Could not insert book
Heres the file that converts the data in the formdata array into an object:
<?php
require_once 'product.php'; //Connecting to the product class
require_once 'Classes/productTable.php'; //Connecting to the TableGateway
require_once 'Classes/Connection.php'; //Connecting to the Connection class
require_once 'validateProduct.php';//Connecting to the product validation
require_once 'utils/functions.php';
//start_session();
//
//if (!is_logged_in()) {
// header("Location: login_form.php");
//}
echo '<pre>';
print_r($_POST);
echo '</pre>';
$formdata = array();
$errors = array();
validate($formdata, $errors);
if (empty($errors)) {
$AuthorName = $formdata['AuthorName'];
$BookName = $formdata['BookName'];
$costPrice = $formdata['CostPrice'];
$sellPrice = $formdata['sellPrice'];
$productCatID = $formdata['productCatID'];
echo '<pre>';
print_r($formdata);
echo 'Form Data array';
echo '</pre>';
$connection = Connection::getInstance();
$gateway = new productTable($connection);
$id = $gateway->insert($AuthorName, $BookName, $costPrice, $sellPrice, $productCatID);
header('Location: viewProducts.php');
}
else {
require 'createProductForm.php';
}
Heres the function in the table gateway that inserts the object into the database:
> public function insert($authorName, $bookName, $costPrice, $sellPrice,
> $productCatID) {
> $sql = "INSERT INTO "
> . "`product`(`AuthorName`, `BookName`, `CostPrice`, `sellPrice`, `productCatID`)"
> . " VALUES (:authorName,:bookName,:costPrice,:sellPrice,:productCatID)";
> $statement = $this->connection->prepare($sql);
> $params = array(
> "authorName" => $authorName,
> "bookName" => $bookName,
> "costPrice" => $costPrice,
> "sellPrice" => $sellPrice,
> "productCatID" => $productCatID
> );
> print_r($params);
> $status = $statement->execute($params);
>
> if (!$status) {
> die("Could not insert book");
> }
>
> $id = $this->connection->lastInsertId();
>
> return $id; }
can somebody please tell me what I'm missing?
Your select has the name of Category_ID not productCatID. If you expecting GET/POST data coming in under productCatID you need to name your select productCatID.
Solved my problem finally, so I'll post how I did it. For debuging my code and to see what values were being passed into the $POST array and the $formdata array, I used print_r to post each array if there was a problem and heres what I got:
$POST Array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[productCatID] => 4
[createProduct] => Create Product
)
form data array
(
[AuthorName] => g
[BookName] => g
[CostPrice] => 33
[sellPrice] => 3
[ProductCatID] =>
)
As you can see the $POST array was getting the value from the drop down list just fine, it was the form data array that was the issue. Embarrassingly the issue was just a simple typo error that was quickly resolved in my validation script.
With foreach you have to explicitly request access to the key, so if you don't, you'll only get the array values.
Just do this to debug (outside of the <select>):
foreach($category as $key=>$cat){
var_dump($cat['ID'], $cat, $key);
}
And I think you'll see where the actual data you need is.
(also, you seem to be running without strict errors and notices on, which is crucial for debugging and might show you some notices when array keys you try to access don't exist)

One checked check box only for each row

I have a table where by each row has 3 columns: name, enable, disable. The enable and disable column have a check box and as the name states, I am trying to do only one ticked checkbox per row. These are my codes (for each row and for the two columns) so far:
<?php foreach($customers as $customer):?>
<tr>
<td align="center"><?php echo $customer;?></td>
<?php
$check = FALSE;
if($user_customer != FALSE)
foreach($user_customer as $object)
foreach($object as $current_customer)
if($current_customer == $customer)
$check = TRUE;
?>
<td align='center'>
<?php
if($check == FALSE)
$data = array('name' => 'enable[]', 'value' => $customer, 'checked' => FALSE);
else
$data = array('name' => 'enable[]', 'value' => $customer, 'checked' => TRUE);
echo form_checkbox($data);
?>
</td>
<td align='center'>
<?php
if($check == TRUE)
$data = array('name' => 'disable[]', 'value' => $customer, 'checked' => FALSE);
else
$data = array('name' => 'disable[]', 'value' => $customer, 'checked' => TRUE);
echo form_checkbox($data);
?>
</td>
</tr>
<?php endforeach?>
After I submit my form it will store the values into the database accordingly however I do not want the user to be able to tick two check boxes at once. I tried using radio buttons but that limits to one check per column. I am trying to make it per row, any help?
P.S. I prefer not to use any Javascript.
EDIT, I added a counter for every row, so it'll be radio_1 for the first row etc, this is the part I edited:
<td align='center'>
<?php
if($check == FALSE)
$data = array('name' => "radio_$counter", 'value' => $customer, 'checked' => FALSE);
else
$data = array('name' => "radio_$counter", 'value' => $customer, 'checked' => TRUE);
echo form_radio($data);
?>
</td>
<td align='center'>
<?php
if($check == TRUE)
$data = array('name' => "radio_$counter", 'value' => $customer, 'checked' => FALSE);
else
$data = array('name' => "radio_$counter", 'value' => $customer, 'checked' => TRUE);
echo form_radio($data);
?>
</td>
EDIT 2, this was how I used to retrieve it in my controller function:
// These were the arrays that I assigned to each checkbox according to the column
$enable = $this->input->post('enable');
$disable = $this->input->post('disable');
// I used it for inserting and deleting values
$insert = $this->home_model->insert_customer(array('user_id'=>$user_id, 'customer'=>$enable));
$delete = $this->home_model->delete_customer($user_id, $disable);
Eventually I managed to solve my problem without using javascript.
First of all, in my view I use one hidden input and one checkbox input in the td. As you can see below, there are two different arrays. The hidden input array is named disable[] and the checkbox array which would contain all the checked checkbox value when form is submitted, is named enable[].
The hidden input array disable[] will always submit the values no matter what. So now we have all the customer names in the disable[] array.
View:
<td align='center'>
<input type="hidden" value="<?php echo $customer?>" name='disable[]'>
<?php
if($check == FALSE)
{
$data = array('name' => 'enable[]', 'value' => $customer, 'checked' => FALSE);
}
else
$data = array('name' => 'enable[]', 'value' => $customer, 'checked' => TRUE);
echo form_checkbox($data);
?>
</td>
Now this is where I manipulate the arrays to get the values I want. In my case, my database table has only two columns which is the user_id and customer. I just add and delete everytime the user wants to enable or disable his/her customer. That's why I want to get both arrays.
Controller:
// Array containing selected/checked customers
$enable = $this->input->post('enable');
// Array containing all customers
$disable = $this->input->post('disable');
// Loop through selected customers
foreach($enable as $index => $value)
{
// Check if customer exists in database
if( $this->home_model->check_customer($user_id, $enable[$index]) )
{
// If exists, unset from enable to prevent duplicate insert
unset($enable[$index]);
}
/* Unset the remaining
(or all selected customers if it doesn't exists in DB)
selected customers from disable array */
$key = array_search($value, $disable);
unset($disable[$key]);
}
Now in the same controller, just do 3 simple checks to see whether the ensure which query to execute, like if there are customers to insert and delete, if there are only customers to insert, or if there are only customers to delete
// Check enable and disable array are not empty
if( ! empty($enable) && ! empty($disable) )
{
$insert = $this->home_model->insert_customer(array('user_id'=>$user_id, 'customer'=>$enable));
$delete = $this->home_model->delete_customer($user_id, $disable);
}
// If enable array is not empty but disable is empty, insert only
elseif( ! empty($enable) && empty($disable) )
{
$insert = $this->home_model->insert_customer(array('user_id'=>$user_id, 'customer'=>$enable));
}
// If enable is empty but disable is not empty, delete only
elseif( empty($enable) && ! empty($disable) )
{
$delete = $this->home_model->delete_customer($user_id, $disable);
}
/*** Proceed with whatever you want to do like go to new page etc ***/

Need to create and return unordered list in PHP class

I am trying to create a list like the following one:
<option value="1">Location 1</option>
<option value="2">Location 2</option>
<option value="3">Location 3</option>
the Public Function in the class should fetch all values from DB to output the results in the format shown above. Here is my function:
public function FitArea(){
$sth = $this->db->prepare("SELECT * FROM `delivery_cost` ORDER BY 'id'");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$FitLocation = array("id" => $row["id"], "location" => $row["location"], "cost" => $row["cost"]);
return $FitLocation;
}
obviously I am calling the class first on the page, but I am not sure if I am doing the rest correctly as nothing simply happens.
<?php
require_once("class/class.get.materials.php");
$getMaterials = new Getmaterials();
$FitLocation = $getMaterials->FitArea();
while($FitLocation > 0){
print<<<END
<option value="{$FitLocation['cost']}">{$FitLocation['location']}</option>
END;
}
?>
I just got it to work, for newbies like myself, here is my detailed answer:
the Public Function should look like the following:
public function FitArea(){
$sth = $this->db->prepare("SELECT * FROM `delivery_cost` ORDER BY id");
$sth->execute();
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
$FitLocation = array();
for($i=0;$i<count($row);$i++){
array_push($FitLocation,
array(
"id" => $row[$i]["id"],
"location" => $row[$i]["location"],
"cost" => $row[$i]["cost"],
)
);
}
return $FitLocation;
}
and the rest should be as follows:
<?php
require_once("class/class.get.materials.php");
$getMaterials = new Getmaterials();
$FitLocation = $getMaterials->FitArea();
foreach($FitLocation as $key => $value){
print<<<END
<option value="{$value['cost']}">{$value['location']}</option>
END;
}
?>
All and all, it feels great when you can figure it out all by yourself
Thanks to all

Codeigniter BUG?: Form validation class getting confused with arrays

I need to create a form with the same group of fields (data is from database)
For example:
Group 1: Description field, Amount field, Others fields
Group 2: Description field, Amount field, Others fields
Group 3: Description field, Amount field, Others fields
So in my view I loop the database values:
$i = 0;
foreach ($data_from_db as $data) {
$description = array(
'name' => 'description[]',
'id' => 'description_field['.$i.']',
'value' => set_value('description[]', $data->description)
);
echo form_label(lang('reward_description'), 'description_field['.$i.']');
echo form_textarea($description);
echo form_error('description[]');
// more fields generated here in similar ways
$i++
}
In my controller I have:
$this->form_validation->set_rules('description[]', 'lang:project_edit_description', 'required');
// more similar rules here
According to the Codeigniter documentation this is the correct way to do it, but its no working correctly.
Codeigniter is getting confused with the validation messages.
For example, if I leave intentionally one of the descriptions fields empty and submit the form, I get the validation error message in all the groups (I get "the Description field is required" also for group 1, 2 and 3)
Just set rules for each indexed field. Following snippets show a working example (Improve it as you require):
Test controller:
function index()
{
if ($_POST)
{
foreach ($_POST as $key => $value)
{
if ($key == 'description' && is_array($value))
{
foreach ($value as $i => $vector)
{
// set rule for each index
$this->form_validation->set_rules('description[' . $i . ']', 'description ' . ($i + 1), 'trim|required');
}
}
}
$this->form_validation->run();
}
$this->load->view('test');
}
Test view views/test.php:
<?php
echo form_open('');
$data_from_db = $_POST ? $_POST['description'] : array('aaa', 'bbb', 'ccc');
$i = 0;
foreach ($data_from_db as $data)
{
$description = array(
'name' => 'description[]',
'value' => set_value('description[]', $data)
);
echo form_label('description ' . ($i + 1) . ':');
echo form_textarea($description);
echo '<br>';
// set error for each index
echo form_error('description[' . $i . ']');
// more fields generated here in similar ways
$i ++;
}
echo form_submit('mysubmit', 'Try it');
echo form_close();
?>
This code will show The description x field is required. only in the empty fields.

Views Exposed Filters as list of links instead of select

Using Drupal 6, Views 2 with exposed filters, I'm trying to determine the best way to convert the select list to a list of links, each with a count of matching nodes. For instance instead of what I get by default, as a select list:
<select name="state" class="form-select" id="edit-state" >
<option value="All" selected="selected"><Any></option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
...
</select>
I'd like to get something like
<p>Restrict results by state:<br />
Alabama (15)<br />
Alaska (7)<br />
...
</p>
With each link showing the count in parentheses and drilling down in the same way that selecting one of the options in the first code block would.
Could you provide any pointers on how to approach this? Thanks.
You may want to look at the Better Exposed Filters module for views. The 7.x version has this functionality and there is a patch for the 6.x version as well which can be found at:
http://drupal.org/node/1159232#comment-4710372
Solr is slick, but also check out the summary option in Views. You can see an example of this in the arguments section of the "Archive list" view that comes with Views.
There are some other faceted browsing modules on drupal.org as well but I haven't got any personal experience with them.
What you are after is not something views was meant to do. It probably would be possible to do, but it will be slow and hard to implement.
Instead you should take a look at the module Acquia has made for Apache Solr. It does faceted search, which is what you really are trying to make. If your case is simple enough you might not need something so fancy. But it's just a matter of time before you do. Performance will become a big issue since you would need to do a query per state to get the counts.
Check this issue http://drupal.org/node/891974.
The code is for the number of posts per page, but can easily be done to other filters too.
<code>
Please go through the following steps to display the select list as year links
//hook_theme
function mymodule_theme($existing, $type, $theme, $path){
return array(
'list_items' => array(
'template' => 'list_items', //tpl to display them as list
'path' => $path . '/templates',
'type' => 'module',
'variables' => array(
'list' => NULL,
'current' => NULL
),
),
);
}
/*
hook_form_alter
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'views_exposed_form') {
$current = '';
$ranges = explode(':',$form['date_filter']['value']['#date_year_range']);
foreach($ranges as $key => $range) {
$ranges[$key] = date('Y', strtotime($range.' years', strtotime(date('Y-m-d H:i:s'))));
}
$startYear = $ranges[0];
$endYear = $ranges[1];
if($ranges[0] > $ranges[1]) {
$endYear = $ranges[0];
$startYear = $ranges[1];
}
$items = array();
$endYear = (int)$endYear;
$startYear = (int)$startYear;
if(empty($_REQUEST['date_filter']['value']['year'])) {
$items[] = 'All years';
} else {
$items[] = l('All years', current_path(),array('query' => array("date_filter[value][year]" => '')) );
}
for($i=$endYear; $i>=$startYear; $i--) {
if($_REQUEST['date_filter']['value']['year'] == $i) {
$items[$i] = $i;
} else {
$items[$i] = l($i, current_path(), array('query' => array("date_filter[value][year]" => $i)));
}
}
$list = theme('list_items', array('list' => $items, 'current' => $_REQUEST['date_filter']['value']['year']));
$form['html'] = array(
'#type' => 'markup',
'#markup' => $list,
);
}
}
/*
templates/list_items.tpl.php
*/
<ol><?php foreach($list as $key => $value) { if($current == $key || empty($current)) { ?><li class="active"><?php print $value; ?></li>
<?php } else { ?> <li><?php print $value; ?></li>
<?php } } ?></ol>
//mymodule.info
name = Filters customization
description = Filters customization
version = VERSION
core = 7.x
dependencies[] = date
</code>

Categories