Solved

Insert an array of dates using codeigniter and active record

Posted on 2013-02-03
10
5,968 Views
Last Modified: 2015-08-05
Hi,
I'm painfully new to codeigniter and am trying to take the values from a form and simply insert into my db. Problem is I have one field (dates) which is an array. In the form the user can dynamically add additional date fields so they are submitted as an array ie: dates[]

I am trying to insert into my db using active record but it dies when it hits the array of dates. Not surprisingly...

My controller looks like:
		// If the form has been posted
		if($this->input->post())
		{
			// Set form validation rules
			$this->form_validation
				->set_rules('contestname', 'Contest Name', 'required|min_length[2]|max_length[200]')
				->set_rules('voice', 'Contest Voice', 'required|min_length[2]|max_length[200]')
				->set_rules('winningcaller', 'Winning Caller', 'required|min_length[2]|max_length[200]')
				->set_rules('dialphone', 'Winning Caller Dials', 'required|min_length[2]|max_length[200]')
				->set_error_delimiters('<div class="error">', '</div>');
			

			
			// Run validation
			if ($this->form_validation->run())
			{
				
				
						
					// Form validation passed.
					$data = array(
						'ContestType'		=> set_value('contesttype'),
						'ContestMode'		=> set_value('contesttype'),
						'ContestName'		=> set_value('contestname'),
						'ContestStartDate'	=> set_value('dates'),
						'Voice'				=> set_value('voice'),
						'WinningNumber'		=> set_value('winningnumber'),
						'DialPhone'			=> set_value('dialphone'),
						'ContestStartMessage'	=> set_value('startmessage'),
						'ContestEndMessage'		=> set_value('endmessage'),
						'PostToFacebook'			=> set_value('facebook'),
						'PostToTwitter'			=> set_value('twitter'),
						'PostToWebsite'			=> set_value('website'),
						'PostToTextMessage'		=> set_value('textmessage'),
						'ContestStop'		=> set_value('contestend'),
						'Description'		=> set_value('description'),
						'account_id'	=> set_value($user_id)
					);
					
					// Add new contest
					$this->contest_model->add($data);
					
					
					$page_view_data->show_succeeded = true;
				}
			}
			else
			{
				// Form validation failed
				$page_view_data->show_form_error = true;
			}
		
		
		// Load the page
		$this
			->require_authentication('user/login')
			->set_page('contests/contest_setup', $page_view_data)
			->set_title('Setup a Contest')
			->load_layout();
	}

Open in new window


My model looks like:

	public function add(array $data)
	{
		$this->db->insert('contest_setup', $data);
		
	}

Open in new window


With the model, I don't have a clue how to handle the dates field when it comes over in the $data object.

The error I get is:
Error Number: 1054

Unknown column 'Array' in 'field list'

INSERT INTO `contest_setup` (`ContestType`, `ContestMode`, `ContestName`, `ContestStartDate`, `Voice`, `WinningNumber`, `DialPhone`, `ContestStartMessage`, `ContestEndMessage`, `PostToFacebook`, `PostToTwitter`, `PostToWebsite`, `PostToTextMessage`, `ContestStop`, `Description`, `account_id`) VALUES ('1', '1', 'Metallica', Array, '0', '', '9024547474', '', '', '', '', '', '', 'on', '', '')

You can see it says simply 'Array' as the value for ContestStartDate which is the date[] array.

Help....
0
Comment
Question by:tjyoung
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 38848986
It depends on how you want the data to be stored.
Multiple values normal ly means multiple records, while you seem to put them all into one. I don't know those classes you are using, so not sure how to solve in either way.
Still hope this gives food to think.
0
 
LVL 27

Accepted Solution

by:
Lukasz Chmielewski earned 500 total points
ID: 38849004
try this way (lose the array keyword):

public function add($data)
	{
		$this->db->insert('contest_setup', $data);
		
	}

Open in new window

0
 
LVL 1

Author Closing Comment

by:tjyoung
ID: 38849013
THANKS VERY MUCH!! Was suffering on this.
0
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 
LVL 1

Author Comment

by:tjyoung
ID: 38849036
Spoke a bit too soon.
the insert works but ignores the dates if I go like this:

ContestStartDate'      => set_value('dates[]'),

if I do this:
ContestStartDate'      => set_value('dates'),

I get the error message again:
Error Number: 1054

Unknown column 'Array' in 'field list'

INSERT INTO `contest_setup` (`ContestType`, `ContestMode`, `ContestName`, `ContestStartDate`, `Voice`, `WinningNumber`, `DialPhone`, `ContestStartMessage`, `ContestEndMessage`, `PostToFacebook`, `PostToTwitter`, `PostToWebsite`, `PostToTextMessage`, `ContestStop`, `Description`, `account_id`) VALUES ('1', '1', 'final', Array, '0', '', '9998889999', '', '', '', '', '', '', 'on', '', '17')



Line Number: 43
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 38849049
How do you want to store an array in MySql database ? What is the field for this ? You cannot store an array in one column for a single database row.
0
 
LVL 1

Author Comment

by:tjyoung
ID: 38849069
Hmm, my scenario is:
A user filling out a form has the option of creating additional date fields by clicking 'add another date'. The field name is dates[] which if I understand things right, that creates an array of values (in my case multiple dates).

So, I thought I would insert the array of dates, perhaps separated by a comma. Done this before for adding multiple checkboxes (example below, unrelated app)
if (isset($_REQUEST['hotbuttons'])) {
 $hotbutton= implode(",", $_REQUEST['hotbuttons']); //concat the string using comma
 mysql_query("UPDATE customers SET hotbuttons = '$hotbutton' ");	
}

Open in new window


You can see how using implode, adds the comma in between each of the values of the array and dumps the whole thing into the hotbuttons column. When I want at the values, I just explode on the commas.

What I'm struggling with is how to do the same kind of thing in this case.
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 38849085
Then you need to implode the required dates value just before model adds it to the database (not tested code, but try below)

public function add($data)
{
      if(is_array($data['ContestStartDate'])) $data['ContestStartDate'] = implode(",", $data['ContestStartDate']);
      $this->db->insert('contest_setup', $data);
}

Open in new window


(edited - removed the array keyword as in original suggestion)
0
 
LVL 1

Author Comment

by:tjyoung
ID: 38849122
That did the trick! Never would have figured it out without your help.
Thanks for your patience.
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 38849133
Glad it worked.
0
 

Expert Comment

by:Puneet Arora
ID: 40916063
I m using this same   logic in my data model , but it is storing single /the last value of the multi select
dropdown : Is there a need for some changes in view , where the drop down is been created . Kindly
answer
0

Featured Post

Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question