Code Igniter- Batch Insert function inserts null fields in database - php

Whenever i try to insert data, the fields of the two of the columns are null. ONLY the auto incremented(of course)MainReqID and the last column had the fields.
Here's my Controller..
public function insert_main($data,$orgs){
$this->db->insert('insert_main',$data);
$getID = $this->db->insert_id();
$ctr=1;
$insertorg = array();
foreach($i=0; $i<count($orgs); $i++){
$insertorg[] = array(
'OrgID'=>$ctr[$i],
'MainID'=>$getID[$i],
'Level'=>'1234'[$i]
);
$ctr++;
}
$this->db->insert_batch('insert_mainreq',$insertorg);
}
here's what it looks like in database...
MainReqID | OrgID | MainID | Level
1 | null | null | 1234
2 | null | null | 1234
3 | null | null | 1234
4 | null | null | 1234
5 | null | null | 1234.. and so on..
i need something like this..
MainReqID | OrgID | MainID | Level
1 | 1 | 3 | 1234
2 | 2 | 3 | 1234
3 | 3 | 3 | 1234
4 | 4 | 3 | 1234
5 | 5 | 3 | 1234.. and so on..

It looks like $getID is not an array but you are adding $getID[i]. This surely will not work. The same with $ctr. This is an integer but you are trying $ctr[i]. The same thing is happening with Level.
public function insert_main($data,$orgs){
$this->db->insert('insert_main',$data);
**$getID** = $this->db->insert_id();
**$ctr=1;**
$insertorg = array();
foreach($i=0; $i<count($orgs); $i++){
$insertorg[] array(
'OrgID'=>**$ctr[$i]**,
'MainID'=>**$getID[$i]**,
'Level'=>**'1234'[$i]**
);
$ctr++;
}
$this->db->insert_batch('insert_mainreq',$insertorg);
}
You could try this, I am not sure what you are trying to do with OrgId and MainID but:
public function insert_main($data,$orgs){
$this->db->insert('insert_main',$data);
$getID = $this->db->insert_id();
$insertorg = array();
foreach($i=0; $i<count($orgs); $i++){
$insertorg[] array(
'OrgID'=> $i,
'MainID'=>$getID,
'Level'=>'1234'
);
}
$this->db->insert_batch('insert_mainreq',$insertorg);
}
Keep in mind that $this->db->insert_id(); will return the id of the last row inserted if there are more than one row.

Try This Code:
public function insert_main($data,$orgs){
$this->db->insert('insert_main',$data);
$getID = $this->db->insert_id();
$insertorg = array();
foreach($i=0; $i<count($orgs); $i++)
{
$insertorg[] = array(
'OrgID'=> $i,
'MainID'=>$getID,
'Level'=>'1234'
);
}
$this->db->insert_batch('insert_mainreq',$insertorg);
}

Related

Looping array and adding, finding same ID's in all rows and columns

Looping array and adding, finding same ID's in all rows and columns.
my table
+-------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
| StdID | day1S1 | day1S2 | day1S3 | day2S1 | day2S2 | day2S3 | day3S1 | day3S2 | day3S3 |
+-------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
| 3 | NULL | 1 | 0 | 1 | 1 | 0 | NULL | 1 | 1 |
| 4 | 1 | 1 | 0 | 1 | 0 | 0 | NULL | 1 | 1 |
| 3 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 1 |
| 3 | NULL | 1 | 0 | 1 | 1 | 0 | NULL | 0 | 0 |
| 4 | 0 | 1 | 1 | 1 | 1 | 0 | NULL | 0 | 0 |
+-------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
I am using the following code
$stu_leave = "SELECT * FROM tblname WHERE StdID = '3' ";
$stu_leave_result = $conn->query($stu_leave);
while($stu_leave_result_fetch = $stu_leave_result->fetch_assoc())
{
$array = array("$day1S1","$day1S2","$day1S3","$day2S1","$day2S2","$day2S3","$day3S1","$day3S2","$day3S3");
$counts = array_count_values($array);
echo $counts['1']."<br>";
echo $counts['0'];
}
Here is my output
5 6 3
2 3 4
I would like to get the result as
14 (add all 5 + 6 + 3).
9
Please help me someone.
You can use array_walk, array_count_values and array_sum to achieve your requirement
$result = [];
array_walk($a, function ($item) use (&$result) {
$item = array_filter($item, function ($var) {
// removing null values
return ($var !== null);
});
$result[] = array_count_values($item);
});
echo array_sum(array_column($result, 1))."<br/>";
echo array_sum(array_column($result, 0));
array_sum — Calculate the sum of values in an array
array_walk — Apply a user supplied function to every member of an array
array_column — Return the values from a single column in the input array
array_filter — Filters elements of an array using a callback function
Output
14
9
Working demo.
EDIT
Mapping to your code,
$result = [];
while($stu_leave_result_fetch = $stu_leave_result->fetch_assoc())
{
$array = array("$day1S1","$day1S2","$day1S3","$day2S1","$day2S2","$day2S3","$day3S1","$day3S2","$day3S3");
$array = array_filter($array, function ($var) {
// fetching null values
return ($var !== null);
});
$result[] = array_count_values($array);
});
echo array_sum(array_column($result, 1))."<br/>";
echo array_sum(array_column($result, 0));
Just sum the values using array_sum().
while ($stu_leave_result_fetch = $stu_leave_result->fetch_assoc()) {
$counts = array_count_values($array);
$sum = array_sum($counts);
echo $sum."<br />\n";
}
First, if you only query the columns that you are actually interested in, the fetched array will only contain the data you want to sum.
You can then do a simple array_sum() on the returned row, making the code a lot simpler and easier to read.
$sql = "SELECT day1S1, day1S2, day1S3, day2S1,
day2S2, day2S3, day3S1, day3S2, day3S3
FROM tblname
WHERE StdID = '3'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
echo array_sum($row) . '<br>';
}

Generating JSON Query Result in Codeigniter

So i have database table named usermeta and have table structure like this :
-----------------------------------------------------------
| ummeta_id | user_id | meta_key | meta_value |
-----------------------------------------------------------
| 1 | 1 | fullname | John Doe |
| 2 | 1 | birthplace | New York |
| 3 | 1 | birthdate | 1990/01/01 |
| 4 | 1 | mobile | 0812-3456-7890 |
| 5 | 1 | email | john.doe#mail.com |
| 6 | 2 | fullname | Jon Wick |
| 7 | 2 | birthplace | Washington DC |
| 8 | 2 | birthdate | 1985/10/21 |
| 9 | 2 | mobile | 0890-1234-5678 |
| 10 | 2 | email | wickjohn#mail.com |
And i try to generate json data for all data from this database using Codeigniter (v 3.1.9) using Controller and Model.
This is my Model (model name: db_usermeta)
function userslist()
{
$query = $this->db->select('*')
->from('usermeta')
->get();
return $query->result();
}
This is my Controller
public function userlist()
{
header('Content-Type: application/json; charset=utf-8');
$query = $this->db_usermeta->userslist();
$json_data = array();
foreach ($query as $key)
{
$json_data[$key->meta_key] = $key->meta_value;
}
echo json_encode($json_data);
}
The result when i open using my browser to check the json data using web developer tool is only show last record, in this case only show data from user_id 2, like this:
{
"fullname":"John Wick",
"birthplace":"Washinton DC",
"birthdate":"1985/10/21",
"mobile":"0890-1234-5678",
"email":"wickjohn#mail.com"
}
What I want to achieve is to show all json data nested like this:
"data": [
{
"fullname":"John Doe",
"birthplace":"New York",
"birthdate":"1990/01/01",
"mobile":"0812-3456-7890",
"email":"john.doe#mail.com"
},
{
"fullname":"John Wick",
"birthplace":"Washinton DC",
"birthdate":"1985/10/21",
"mobile":"0890-1234-5678",
"email":"wickjohn#mail.com"
}
]
How can i achieve this? Did I make a mistake on my controller and model. I really appreciate your help.
your $key->meta_key is overwriting for every record. that's why only last record appeared. You don't actually need to loop through to get json data.
public function userlist()
{
header('Content-Type: application/json; charset=utf-8');
$query = $this->db_usermeta->userslist();
$json_data = array(array());
$user_id_map = array();
$index = 0;
foreach ($query as $key)
{
if(!isset($user_id_map[$key->user_id])){
$user_id_map[$key->user_id] = $index++;
}
$currentIndex = $user_id_map[$key->user_id];
$json_data[$currentIndex][$key->meta_key] = $key->meta_value;
}
echo json_encode($json_data);
}
just change your controller code to this and this will return json data.
Since the meta key fullname is same for both records, you need to change the key name to something unique
foreach ($query as $key)
{
$json_data[$key->meta_key] = $key->meta_value;
}
Change $json_data[$key->meta_key] to $json_data[$key->meta_key.$key->user_id]
or simply change it to $json_data[$key->ummeta_id]

How can I join into insert statement?

Here is my table structure:
// pages
+----+-----------------------+--------+
| id | path | method |
+----+-----------------------+--------+
| 1 | list_role | get |
| 2 | make_role | post |
| 3 | edit_role/id | get |
| 4 | list_voucher/activate | get |
| 5 | list_voucher/activate | post |
| 6 | expire_voucher/id | get |
+----+-----------------------+--------+
// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
Now I want to insert multiple rows into role_page table according to this array: (noted that I have $role_id)
$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example
So the expected output is:
// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
| 4 | 1 |
| 4 | 4 |
+---------+---------+
How can I do that by a join?
Currently I do that by a loop on $arr like this:
$role_id = 4;
foreach($arr as $row) {
// match the page id
$page_id = pages::where('path', row[0])->where('method', row[1])->first();
// insert
$role_page = new role_page;
$role_page->role_id = $role_id;
$role_page->page_id = $page_id;
}
Try this
Page Model (you may have to customize this relation)
public function roles(){
return $this->belongsToMany(Role::class, 'role_page', 'page_id', 'role_id')
}
Then
$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example
$query = Page::query();
foreach ($arr as $page){
$query = $query->orWhere(function($query){
$query->where('path', $page[0])->where('method', $page[1]);
}
}
$pages =$query->get();
foreach($pages as $page){
$page->roles()->attach($role_id);
}
$page_id = pages::where('path', row[0])->where('method', row[1])->first();
This returns an object.
$page_id = pages::where('path', row[0])->where('method', row[1])->first()->id;
This will return just the id.
And then in your foreach you can:
role_page::create([
'page_id' => $page_id,
'role_id' => $role_id
]);
You do have to explicitly state in your role_page model that it's not plural if your not refering to it in a relationship way:
protected $table = 'role_page';

Find insert position and number of childs in a binary tree using php mysql

below is my table data
+-------------+-----------+----------------+
| customer_id | parent_id | node_direction |
+-------------+-----------+----------------+
| 1 | 0 | T |
| 2 | 1 | L |
| 3 | 1 | R |
| 4 | 2 | L |
| 5 | 2 | R |
| 6 | 4 | L |
+-------------+-----------+----------------+
Which represents the following tree
1
|
---------
| |
2 3
|
-------
| |
4 5
|
-----
|
6
I need to find the position for insertion by parent id
For Example:
1) if parent id is 1 then insert position will be root-3 position-L
2) if parent_id is 2 then insert position will be root-4 position-R
3) if parent_id is 3 then insert position will be root-3 position-L
The thing is it need to follow the binary structure
I also need to have count of sub nodes by parent node for example:
1 - 5
2 - 3
3 - 0
4 - 1
5 - 0
I need to accomplish this in php and mysql.
Can anyone suggest to me the easiest way to achieve this?
function getNodeInsertPostionByParentId($parentId){
$position = array('status'=>false);
$parents = array();
foreach($parentId as $parent){
$qry = "select customer_id,node_direction from mlm_nodes where parent_id =".$parent." order by node_direction";
$rst = mysql_query($qry);
$count = mysql_num_rows($rst);
if($count==2){
while($row = mysql_fetch_assoc($rst)){
$parents[$parent][] = $row['customer_id'];
}
}elseif($count==1){
$position['status'] = true;
$position['parentId'] = $parent;
$position['node'] = 'R';
//echo '<pre>1';print_r($position);echo '</pre>';
return $position;
}else{
$position['status'] = true;
$position['parentId'] = $parent;
$position['node'] = 'L';
//echo '<pre>2';print_r($position);echo '</pre>';
return $position;
}
}
return $this->searchByParents($parents);
}
function searchByParents($parents){
foreach($parents as $parent){
return $this->getNodeInsertPostionByParentId($parent);
}
}
echo '<pre>';print_r($this->getNodeInsertPostionByParentId(array('4')));die;
This works as expected for finding node position by parent id

PHP MySQL code optimize

Is there any MySQL function that will optimize this code? A child ID getting all parent ID
function get_parents() {
$ids = array();
while($id) :
$query = "SELECT placement_id FROM referrals WHERE user_id = $id";
$query = $this->db->query($query);
$result = $query->row();
if(!isset($result->placement_id)) :
break;
elseif(isset($result->placement_id) && $result->placement_id == 2) :
break;
endif;
$id = $result->placement_id;
array_push($ids, $id);
if($result) :
continue;
endif;
break;
endwhile;
return $ids;
}
The code above will return all parent ID of given user_id, this will stop if nothing is found. I found this code too slow and heavy load.
My Table
relations table
| id | user_id | placement_id |
| 1 | 2 | NULL |
| 2 | 3 | 2 |
| 3 | 4 | 2 |
| 4 | 5 | 3 |
| 5 | 6 | 4 |
| 6 | 7 | 3 |
| 7 | 8 | 3 |
| 8 | 9 | 3 |
| 9 | 10 | 6 |
| 10 | 11 | 5 |
| 11 | 12 | 6 |
| 12 | 13 | 4 |
| 13 | 14 | 3 |
| 14 | 15 | 9 |
| 15 | 16 | 10 |
user_id is the child and parent is placement_id
You can rewrite you code as:
function get_parents() {
$ids = array();
while($id){
$query = "SELECT placement_id FROM referrals WHERE user_id = $id";
$query = $this->db->query($query);
$result = $query->row();
if(isset($result->placement_id) && $result->placement_id !== 2)
{
$id = $result->placement_id;
array_push($ids, $id);
}
}
return $ids;
}
It excludes some additional function calls such continue,break etc. Also, Make sure you have INT as type of user_id with indexing on this column.
I would personally do something like this:
<?php
define('MAX_NEST_DEPTH', 15);
function get_parent($child_id) {
$child_id = (int) $child_id;
$parents = array();
$counter = 0;
do {
$sql = "SELECT placement_id
FROM referrals
WHERE user_id = {$child_id}";
$query = $this->db->query($query);
$result = $query->row();
$child_id = (int) $result->placement_id;
$parent[] = $child_id;
$counter++;
}
while ($child_id != 0 || $counter == MAX_NEST_DEPTH);
return $parents;
}
You wont get around the query in a loop here, mysql does not support n-level-nested SELECT, otherwise we could just do it in one go.

Categories