CodeIgniter multidimensional array store in mysql database single column - php

I am trying to store this data in database but i am getting error. how to fix this?
I want simply store multidimensional array in a single column.
$data = array(
'2017' => array(
'6' => array(
'10' => array(
'count' => 76
),
),
),
);
$getdata = $this->view_count->setView($data);
Model
public function setView($data)
{
$setData = $this->db->where('short', 'honwl')->update('ci_links', $data['view_count']);
return $setData;
}
Error which i am getting
A PHP Error was encountered
Severity: Notice
Message: Undefined index: view_count
Filename: models/View_count.php
Line Number: 14
Backtrace:
File: C:\wamp\www\blog\application\models\View_count.php
Line: 14
Function: _error_handler
File: C:\wamp\www\blog\application\controllers\Dashbord.php
Line: 52
Function: setView
File: C:\wamp\www\blog\index.php
Line: 315
Function: require_once
A Database Error Occurred
You must use the "set" method to update an entry.
Filename: C:/wamp/www/blog/system/database/DB_query_builder.php
Line Number: 1864

As message says, you don't have key $data['view_count'] but you have $data[2017][6][10]['count'] value. I asume those dates are changed dynamically so you need to get value of inner array by key count.
If your array always has similar keys i.e. $data[year][month][day][count], you can use code (bit modified) from this answer to get that key value. Put in your model
private function getCount($arr, $search)
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($iterator as $key => $value) {
if($search == $key && $value !== '') {
return $value;
}
}
return false;
}
Then in your first method use value filtered through this function:
public function setView($data)
{
$count = $this->getCount($data, 'count');
if ($count !== false) {
$setData = $this->db->where('short', 'honwl')->update('ci_links', $count);
return $setData;
}
return false;
}

According to you example code, you can encode array data to JSON for saving to column, then get back by decode:
Controller:
$data = array(
'2017' => array(
'6' => array(
'10' => array(
'count' => 76
),
),
),
);
$getdata = $this->view_count->setView($data);
$data = $this->view_count->getView();
Model:
public function setView($data)
{
$data = json_encode($data);
$setData = $this->db->where('short', 'honwl')->update('ci_links', array('column_name'=>$data));
return $setData;
}
public function getView($data)
{
$row = $this->db->where('short', 'honwl')->get('ci_links')->row();
return json_decode($row->column_name, true);
}
The column_name depends on your table's column name that save the array data.

Related

How to UPDATE Multiple table using Postgresql & Codeigniter

I have data in the form of array and i want them to be updated into multiple table. Im using Codeigniter and Postgresql
Here is my controller
public function update()
{
$where = array(
'id' => $this->input->post('id')
);
$data = array(
'case_name' => $this->input->post('txtCaseName'),
'firm_name' => $this->input->post('txtFirmName'),
'case_description' => $this->input->post('txtCaseOverview'),
'service_names' => $this->input->post('txtDesiredServices'),
'instruction' => $this->input->post('txtinstruction'),
);
//print_r($data);
//die;
$this->HomeModel->update($data, $where);
This is my Model:
var $table = array('tracker.case_main,
tracker.case_overview,
tracker.type_of_services,
tracker.instructions');
//(tracker is my scheme name)
public function update($data, $where)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
Error im receiving :
Error Number: 42601/7
ERROR: syntax error at or near "Array"
LINE 1: UPDATE Array SET "case_name" = 'Mary Garner', "firm_name" =...
^UPDATE Array SET "case_id" = 'Medidoco_001sa', "case_name" = 'Mary Garner', "firm_name" = 'xyz', "case_description" = '', "service_names" = '', "instruction" = '', WHERE "id" = '78'Filename: C:/xampp/htdocs/casetrackings/system/database/DB_driver.phpLine Number: 691
im new to php and codeigniter :P

Laravel trying to get property of non-object in an object

Simple code will not work! I keep getting the error Trying to get property of non-object on the line with the if statement. I tried accessing this like an array I get a message saying it can't access a stdClass as an Array.
public function isAllowed($perm)
{
$cando = 0;
$groups = DB::table('group_user')->where('user_id', $this->id)->get();
foreach ($groups as $mygroup)
{
$group_can = DB::table('group_permission')->where([
['permission_id', $permission->id],
['group_id', $mygroup->group_id]
])->first();
$setting = $group_can->setting; // Error returns for this line //
if ($setting > $cando)
{
$cando = $setting;
}
}
}
print_r, var_dump, and dd of $group_can give this:
stdClass Object
(
[group_id] => 1
[permission_id] => 50
[setting] => 1
)
object(stdClass)#555 (3) { ["group_id"]=> int(1) ["permission_id"]=> int(50) ["setting"]=> int(1) }
{#555 ▼
+"group_id": 1
+"permission_id": 50
+"setting": 1
}
Using $setting = $group_can->setting; returns the error Trying to get property of non-object
Using $setting = $group_can['setting']; returns the error Cannot use object of type stdClass as array
The details of the laravel error are:
at HandleExceptions->handleError(8, 'Trying to get property of non-object', '/home/mwsubmissions/public_html/jon/MWSubmissionManager/app/User.php', 91, array('perm' => 'manage.projects', 'cando' => 1, 'groups' => object(Collection), 'permission' => object(stdClass), 'mygroup' => object(stdClass), 'group' => null, 'group_can' => null, 'setting' => 1))
EDIT
I removed the first part of the code that I was having errors with and then got to this, another example of the same thing, but using a smaller object and this line is more important than the last was. All details updated.
Better you can check isset
public function isAllowed($perm)
{
$cando = 0;
$groups = DB::table('group_user')->where('user_id', $this->id)->get();
if(isset($groups)&&count($groups)>0){
foreach ($groups as $mygroup)
{
if(isset($mygroup->group_id)){
$group = Group::find($mygroup->group_id);
}
if (!is_null($group->project_id))
{
continue;
}
}
}
}
The property you're trying to access is an element of an array 'attributes', so try:
public function isAllowed($perm)
{
$cando = 0;
$groups = DB::table('group_user')->where('user_id', $this->id)->get();
foreach ($groups as $mygroup)
{
$group = Group::find($mygroup->group_id);
if (!is_null($group->attributes['project_id']))
{
continue;
}
}
}
Hope this helps :)
First, ensure you add "project_id" to $fillable array in Group Model
Try this
public function isAllowed($perm)
{
$cando = 0;
$groups = DB::table('group_user')->where('user_id', $this->id)->get();
foreach ($groups as $mygroup)
{
$group = Group::whereId($mygroup->group_id)->first();
if (!is_null($group->attributes['project_id']))
{
continue;
}
}
}

Codeigniter - how to passing foreach value to inside of array

I use CodeIgniter 3 and libraries of http://biostall.com/codeigniter-google-maps-v3-api-library/ .
When I take the data from the database and put it into the polygon points, I encountered some error .
Severity: Warning Message: trim() expects parameter 1 to be string,
array given Filename: libraries/Googlemaps.php
Line Number: 2179
my controller function :
public function testing()
{
$config['center'] = '-8.1768084, 113.6559507';
$config['zoom'] = 'auto';
$this->googlemaps->initialize($config);
$kecamatan = $this->Peta_model->get_kecamatan();
foreach ($kecamatan as $k) {
$kcmt = $k->name;
$coor = $this->Peta_model->get_coor_by_kcmt($kcmt);
if ($coor) {
$polygon = array(
'points' => array() ,
'strokeColor' => '#000099' ,
'fillColor' => '#000099' ,
);
foreach ($coor as $c) {
$polygon ['points'][] = array("'".$c->latitude.",".$c->longitude."'");
}
$this->googlemaps->add_polygon($polygon);
}
}
$user = $this->ion_auth->user()->row();
$user_level = $this->ion_auth->get_users_groups($user->id)->row();
$data = array(
'user' => $user ,
'user_level' => $user_level ,
'title' => 'Peta' ,
'content' => 'peta/v_peta' ,
'map' => $this->googlemaps->create_map(),
);
$this->load->view('dashboard/layout', $data);
}
normaly add polygon is :
$polygon = array(
'points' => array('37.425, -122.1321',
'37.4422, -122.1622',
'37.4412, -122.1322',
'37.425, -122.1021') ,
'strokeColor' => '#000099' ,
'fillColor' => '#000099' ,
);
$this->googlemaps->add_polygon($polygon);
how do I fix it ?
You are storing an array in $polygon ['points'][].
i think you should store a string. like..
$polygon ['points'][] = "'".$c->latitude.",".$c->longitude."'";
Solved !. only cahange
$polygon ['points'][] = array("'".$c->latitude.",".$c->longitude."'");
to
$polygon ['points'][] = $c->latitude.','.$c->longitude;
thank you #Muhammad Suhaib

What is the best way to access unknown array elements without generating PHP notice?

If I have this array,
ini_set('display_errors', true);
error_reporting(E_ALL);
$arr = array(
'id' => 1234,
'name' => 'Jack',
'email' => 'jack#example.com',
'city' => array(
'id' => 55,
'name' => 'Los Angeles',
'country' => array(
'id' => 77,
'name' => 'USA',
),
),
);
I can get the country name with
$name = $arr['city']['country']['name'];
But if the country array doesn't exist, PHP will generate warning:
Notice: Undefined index ... on line xxx
Sure I can do the test first:
if (isset($arr['city']['country']['name'])) {
$name = $arr['city']['country']['name'];
} else {
$name = ''; // or set to default value;
}
But that is inefficient. What is the best way to get $arr['city']['country']['name']
without generating PHP Notice if it doesn't exist?
I borrowed the code below from Kohana. It will return the element of multidimensional array or NULL (or any default value chosen) if the key doesn't exist.
function _arr($arr, $path, $default = NULL)
{
if (!is_array($arr))
return $default;
$cursor = $arr;
$keys = explode('.', $path);
foreach ($keys as $key) {
if (isset($cursor[$key])) {
$cursor = $cursor[$key];
} else {
return $default;
}
}
return $cursor;
}
Given the input array above, access its elements with:
echo _arr($arr, 'id'); // 1234
echo _arr($arr, 'city.country.name'); // USA
echo _arr($arr, 'city.name'); // Los Angeles
echo _arr($arr, 'city.zip', 'not set'); // not set
The # error control operator suppresses any errors generated by an expression, including invalid array keys.
$name = #$arr['city']['country']['name'];

Insert several array of value different in new row from database

I want insert in the row from database, array of values as that each of they put in new row from database.
I not want insert all values in a row from database with use of serialize(json_encode or etc).
For example:(in this example, i want three times insert data(value), because i have 3 value different)
Update 4:
this my value:
<input name="name[0][]" value="11">
<input name="passport_number[0][]" value="11">
<input name="name[1][]" value="22">
<input name="passport_number[1][]" value="22">
i do it, but it not worked:
$name_input = $this->input->post('name');
$passport_number_input = $this->input->post('passport_number');
//$term_passport_input = $this->input->post('term_passport');
//$date_of_birth_input = $this->input->post('date_of_birth');
//$age_input = $this->input->post('age');
//$national_number_input = $this->input->post('national_number');
//$mobile_input = $this->input->post('mobile');
//$address_input = $this->input->post('address');
$data = array();
foreach ($name_input as $idx => $name) {
$data[] = array(
'name' => $name_input[0]
'passport_number' => $passport_number_input[0],
//'term_passport' => $term_passport_input[$idx],
//'date_of_birth' => $date_of_birth_input[$idx],
//'age' => $age_input[$idx],
//'national_number' => $national_number_input[$idx],
//'mobile' => $mobile_input[$idx],
//'address' => $address_input[$idx],
);
};
var_dump($name_input);
$this->db->insert_batch('customer_info', $data);
This is output '$name_input' with var_dump:
array(2) {
[0] = > array(1) {
[0] = > string(2)"11"
}[1] = > array(1) {
[0] = > string(2)"22"
}
}
I get this error:
A PHP Error was encountered Severity: Warning Message: Cannot
modify header information - headers already sent by (output started at
D:\xampp\htdocs\application\controllers\admin\tour_foreign.php:405)
Filename: core/Common.php Line Number: 413 A Database
Error Occurred Error Number: 1054 Unknown column '0' in 'field
list' INSERT INTO customer_info (0) VALUES ('22')
Filename: D:\xampp\htdocs\system\database\DB_driver.php Line
Number: 330
Update 3: Per updated question (update 4)
Looking at the var_dump of $name_input following code should work:
$name_input = $this->input->post('name');
$passport_number_input = $this->input->post('passport_number');
$data = array();
foreach ($name_input as $idx => $name) {
$data[] = array(
'name' => $name_input[$idx][0],
'passport_number' => $passport_number_input[$idx][0]
);
};
$this->db->insert_batch('customer_info', $data);
It is further needed to access the [0] element as the POST input is passes as an array of arrays
Update 2:
Seeing the problem is because the POST returns the data as a further array following code MIGHT work. I would need var_dump of POST inputs ($hi_input..) to give the exact code.
$hi_input = $this->input->post('hi');
$hello_input = $this->input->post('hello');
$how_input = $this->input->post('how');
$data = array();
foreach ($hi_input as $idx => $name) {
$data[] = array(
'hi' => $hi_input[$idx][0],
'hello' => $hello_input[$idx][0],
'how' => $how_input[$idx][0]
);
};
$this->db->insert_batch('table', $data);
The following code should work as I have tested it (I do not have CodeIgniter Installed). It does not use CodeIgniter to get post data.
$hi_input = $_POST['hi'];
$hello_input = $_POST['hello'];
$how_input = $_POST['how'];
$data = array();
foreach ($hi_input as $idx => $name) {
$data[] = array(
'hi' => $hi_input[$idx][0],
'hello' => $hello_input[$idx][0],
'how' => $how_input[$idx][0]
);
};
$this->db->insert_batch('table', $data);
Update :
You can also do this using $this->db->insert_batch();, like this :
$hi_input = $this->input->post('hi');
$hello_input = $this->input->post('hello');
$how_input = $this->input->post('how');
$data = array();
foreach ($hi_input as $idx => $name) {
$data[] = array(
'hi' => $hi_input[$idx],
'hello' => $hello_input[$idx],
'how' => $how_input[$idx]
);
};
$this->db->insert_batch('table', $data);
Old answer
The CodeIgniter documentation on insert - http://codeigniter.com/user_guide/database/active_record.html#insert
states that the $data parameter is an associative array with column names as keys and data to insert as values.
So you need to call it once for each row. Thus
Try this:
$hi_input = $this->input->post('hi');
$hello_input = $this->input->post('hello');
$how_input = $this->input->post('how');
foreach ($hi_input as $idx => $name) {
$data = array(
'hi' => $hi_input[$idx],
'hello' => $hello_input[$idx],
'how' => $how_input[$idx]
);
$this->db->insert('table', $data);
};

Categories