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);
};
Related
Hi I have an array like this:
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
]
foreach($datas as $data){
//get items here...
}
How to pair or parse those items to make insert statement like this:
INSERT INTO table (name, settings)VALUES('John','Settings 1');
INSERT INTO table (name, settings)VALUES('Mickey','Settings 2');
Any idea? Thanks in advance.
This code could be usefull for creating array of arrays. Considering array keys will be name_x and settings_x
foreach($datas as $key=>$value){
// explode each key of the array
$keys = explode('_',$key);
$name = 'name_'.$keys[1];
$settings = 'settings_'.$keys[1];
// to generate array
$new_array[$keys[1]]=array('name'=>$datas[$name], 'settings'=>$datas[$settings]);
}
print_r($new_array);
Loop the $new_array for insert query.
Output :
Array
(
[1] => Array
(
[name] => John
[settings] => Settings 1
)
[2] => Array
(
[name] => Mickey
[settings] => Settings 2
)
)
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
];
$results = [];
foreach($datas as $index=>$data){
//create an array out of $index breaking it at the '_'
//so array will be $parts = [0=>'name', 1=>'1'];
$parts = explode('_', $index);
//'name_1'=>'John' = $results[1]['name'] = 'John';
$results[$parts[1]][$parts[0]] = $data;
}
//batch insert new formed array
//INSERT INTO tbl_name (name, settings) VALUES $results;
Check this, you must do some intermediate steps. Comments on code!!
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
];
$data_final = [];
foreach($datas as $key=>$value){
$keyX = preg_replace('/^(.+)_(\d+)$/', '$1', $key);// get the "type" (name, setting)
$keyY = preg_replace('/^(.+)_(\d+)$/', '$2', $key);// get the "index" (_1, _2 without "_")
$data_final[$keyY][$keyX] = $value; // put in result
}
// make queries
$sql = [];
foreach($data_final as $datas){
$fields = implode(", ", array_keys($datas)); //implode the keys to sql fields
$values = implode(", ", array_map(function($a){return "'$a'";}, array_values($datas)));//implode values to sql values adding ''. WARNING: This not escape values. Use escape string function on mysqli obj or PDO to the right escape
$sql[] = "INSERT INTO table ($fields) VALUES ($values);"; // populate query
}
$sql = implode("\n", $sql); // implode with new line
print_r($sql); //results
IMPORTANT:
You must have the right syntax "field_number" to respect the procedure
You can use even with one or more of two fields per record
You can use any field name, always respecting the "field_number" syntax
DEMO HERE
I am getting this error
Unknown column 'Array' in 'field list'
When inserting checkbox list into database. When I do print_array I am getting this result :
Array
(
[0] => Array
(
[user_id] => 3
[project_id] => 10
[project_type] => 5
[project_list] => Array
(
[0] => 17
[1] => 18
)
)
)
The project_list value supposed to be inserted into a new row in the database.
my view : <input type="checkbox" value="<?php echo $project_list['id']; ?>" name="project_list[]"> which is populated from database.
my controller : $this->Project_module->createProject($_POST['project_list']);
my module
public function createProject($project_list){
if($project_list != null){
$data = array();
foreach($project_list as $project_list){
$data[] = array(
'user_id' => $this->getUserId(),
'project_id' => $this->getProjectId(),
'project_type' => $this->getProjectType(),
'project_list' => $this->getProjectList(),
);
}
$this->db->insert_batch('tblProject', $data);
if($this->db->affected_rows()){
return true;
} else {
return false;
}
}
}
EDIT
I was edited my foreach like this
foreach($project_list as $row){
$data = array(
'user_id' => $this->getUserId(),
'project_id' => $this->getProjectId(),
'project_type' => $this->getProjectType(),
'project_list' => $this->getProjectList(),
);
}
But I am still getting the same error.
Linundus, you need to name the array alias in the foreach something different. You have
foreach ($project_list as $project_list)
you need to have something like this:
foreach($project_list as $list)
You already pass the project_list So you don't want to get the list again. And you can store the just foreach string. In my side confusion with $data and $data[] So test with both and let me know....
Please check before with Table fields are correct
public function createProject($project_list){
if($project_list != null){
$data = array();
foreach($project_list as $row){
$data[] = array(
'user_id' => $this->getUserId(),
'project_id' => $this->getProjectId(),
'project_type' => $this->getProjectType(),
'project_list' => $row,
);
}
$this->db->insert_batch('tblProject', $data);
if($this->db->affected_rows()){
return true;
} else {
return false;
}
}
}
I have solved the problem and here is my coding that working fine now.
ERROR CAUSE
In the controller I have already set the checkbox setter like this :
$this->Project_module->setProjectList($this->input->post('project_list'));
and then call the createProject function after like this :
$this->Project_module->createProject($_POST['project_list']);
So I am getting error with the foreach inside my module.
SOLUTION
In controller
Remove this line
$this->Project_module->setProjectList($this->input->post('project_list'));
Simply hold all checkbox value in line
$this->Project_module->createProject($_POST['project_list']);
And in module
public function createProject($project_list){ // $_POST['project_list'] value pass in $project_list
if($project_list != null){
$data = array();
foreach($project_list as $row){ // Do foreach to insert every value in different rows in database
$data[] = array(
'user_id' => $this->getUserId(),
'project_id' => $this->getProjectId(),
'project_type' => $this->getProjectType(),
'project_list' => $row,
);
}
$this->db->insert_batch('tblProject', $data);
if($this->db->affected_rows()){
return true;
} else {
return false;
}
}
}
Array
(
[0] => Array
(
[user_id] => 3
[project_id] => 10
[project_type] => 5
[project_list] => Array
(
[0] => 17
[1] => 18
)
)
)
your value is in a nested key 0 so if you want to access project_id you'll have to use $array[0]['project_id']
a suggestion here would be to you check if values inside key 0 exist then do print
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.
I need to dynamically build a complex MongoDB query before executing it in PHP. My query line looks like $cursor = $c_sbc->aggregate($query_string);, where $query_string is something like [['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000', -1]]]]].
Copy-and-pasting the above-given example to replace $query_string gives the desired result. However, running it with $query_string in place gives an error saying it expects an array, not a string. How do I get this query to work?
Catchable fatal error: Argument 1 passed to MongoDB\Collection::aggregate() must be of the type array, string given, called in C:\xampp\htdocs\gc5\screen.php on line 60 and defined in C:\xampp\htdocs\gc5\vendor\mongodb\mongodb\src\Collection.php on line 163
Edit: relevant PHP
$query = $_POST['screen'];
$t = array(
"revenue" => 1000,
"costofgoodssold" => 1001
);
$data_array = [];
//turn words into data.XXXX codes
function translate($match){
global $t;
global $data_array;
foreach($match as $m){
$d = "data.".$t[$m];
$data_array[] = $d;
return $d;
}
}
$query = preg_replace('/\s/', '', $query); //strip whitespace
$query = strtolower($query);
$query = preg_replace_callback('/([A-Z]+)/i','translate', $query);
echo "<br>Query: ";
print_r($query);
echo "<br>";
$client = new MongoDB\Client("mongodb://localhost:27017");
$db = $client->gc_dev;
$c_sbc = $db->screenByCompany;
$for_years = [-1]; //default is TTM
$symbols = ['goog', 'fb', 'crmt', 'vlgea', 'ko', 'pep', 'flws'];
for($i=0;$i<count($symbols);$i++){
$sym = $symbols[$i];
for($j=0;$j<count($for_years);$j++){
$k = $for_years[$j];
//build query for data
$data_query = "";
foreach($data_array as $d){
if($data_query == ""){ //first go-around, no need for comma
$data_query .= "['first' => ['\$arrayElemAt' => ['$".$d."', ".$k."]]]";
}else{
//$data_query .= ",['second' => ['\$arrayElemAt' => ['$".$d."', ".$k."]]]";
}
$query_string = "[['\$match' => ['symbol' => \$sym]],['\$project' => ".$data_query."]]";
}
echo "<br>\$query_string: ".$query_string;
$cursor = $c_sbc->aggregate($query_string);
//$cursor = $c_sbc->aggregate([['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000',-1]]]]]);
$cursor = iterator_to_array($cursor);
//var_dump($cursor);
echo "Cursor: ".$cursor[0]['first'] . "<br><br>";
}
Results in:
Query: (data.1000-data.1001)>1,000
$query_string: [['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000', -1]]]]]
Catchable fatal error: Argument 1 passed to MongoDB\Collection::aggregate() must be of the type array, string given, called in C:\xampp\htdocs\gc5\screen.php on line 60 and defined in C:\xampp\htdocs\gc5\vendor\mongodb\mongodb\src\Collection.php on line 163
Found your error. You are declaring $query_string as a string and not as an array like what the function aggregate is asking for. Your code is:
$query_string = "[['\$match' => ['symbol' => \$sym]],['\$project' => ".$data_query."]]";
Replace it with:
$query_string = [['\$match' => ['symbol' => \$sym]],['\$project' => $data_query]];
I have created an array, one of the is intended to be a string used by php to display a field from a record retrieved from sqlite3.
My problem is that ... it doesn't.
The array is defined, "1" being the first database field, and "2" is the second database field:
EDIT : I have re-defined the problem as a script so you can see the whole thing:
//If I have an array (simulating a record retrieved from database):
$record = array(
name => 'Joe',
comments => 'Good Bloke',
);
//then I define an array to reference it:
$fields = array(
1 => array(
'db_index' => 'name',
'db_type' => 'TEXT',
'display' => '$record["name"]',
'form_label' => 'Name',
),
2 => array(
'db_index' => 'comments',
'db_type' => 'TEXT',
'display' => '$record["comments"]',
'form_label' => 'Comments',
),
);
//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";
//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
{
$label = $field['form_label'];
$it = $field['display'];
$line = "\"$label = \" . $it .\"\n\"";
print $line;
}
Output:
Expected output:
Name = Joe
Comments = Good Bloke
Output using Array values:
Name = $record["name"]
Comments = $record["comments"]
Don't call variable from string. Just concatenate it :
foreach($GLOBALS["fields"] as $field){
$label = $field['form_label'];
$it = $field['display'];
eval("$it = ".$it);
$line = $label." = ".$it."\n";
print $line;
}
Well, how do it looks ?