Solved

Insert an array of dates using codeigniter and active record

Posted on 2013-02-03
10
5,752 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
10 Comments
 
LVL 142

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
 
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

947 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now