Create an array in config in Codeigniter?

I am working with a configuration file that I created to store users. This, of course, is not what was intended for configurations, but it is a very small application, and I think that would be a good solution.

My array looks like this:

$config['users'] = array(array('username' => 'username', 'password' => 'password')); 

It works well. I can quickly and easily get information. BUT, if I try to write a new array (new user) to the configuration file, I get this error: Invalid offset type in isset or empty

I use $this->config->item('users', array('username' =>....)) which does not support arrays.

How can I write arrays to my configuration variable? Is there another way?

EDIT: Well, the bug is fixed thanks to the answer provided by phirschy. I was so sure in my head that I could use config-> item () that I did not check the manual for config-> set_item () ... BUT, it still doesn't work. Here is the specific code:

  $users = $this->config->item('users'); array_push($users, array('username' => $this->input->post('username'), 'password' => $this->input->post('password'))); $this->config->set_item('users', json_encode($users)); echo json_encode($users); 

This code is called through Ajax, and I have a warning window to see if the values ​​are correct. They are. And, as you can see, I tried to save it as json instead of an array ... but this does not work either. Help me please?

Thank you

+6
php codeigniter
source share
2 answers

You should use the set_item method to write the configuration item, not "item":

 $this->config->set_item('item_name', 'item_value'); 

Or in your case:

 $this->config->set_item('users', array(...)); 
+5
source share

Old question, but I had a similar question. So:

And as you can see, I tried to save it as json instead of an array as well .... but this also does not work.

It should have been the first to be reckless that something else is wrong - JSON is just a string. If you could not keep it, something else was wrong. Indeed, your code is confusing and a little suspicious, you are storing JSON (string), but you are accessing it as if it were an array (without json_decode somewhere).

Anyway, I would suggest a simple test:

 $this->config->set_item('the_array', array("I'm", "an", "array")); echo 'The config array: '.print_r($this->config->item('the_array'), true); 

I ended up trying to do this after seeing your question with the final answer - it works fine in CodeIgniter 1.7. So the answer is yes, you can store arrays as configuration items. No JSON encoding required.

Greetings

0
source share

All Articles