how to read multiple value from joined table in codeigniter - php

how to read multiple value from joined table in codeigniter
this is model.php
public function all_village_info($id = NULL) {
$this->db->select('tbl_village.*', FALSE);
$this->db->select('tbl_school.*', FALSE);
$this->db->from('tbl_village');
$this->db->join('tbl_school', 'tbl_school.school_id=tbl_village.school_id', 'left');
if (!empty($id)) {
$this->db->where('tbl_village.village_id', $id);
$query_result = $this->db->get();
$result = $query_result->row();
} else {
$query_result = $this->db->get();
$result = $query_result->result();
}
return $result;
}
and this is view.php
<table class="table table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th class="col-sm-1" >VILLAGE</th>
<th class="col-sm-1" >ZONE</th>
<th class="col-sm-1" >SCHOOL</th>
</tr>
</thead>
<tbody>
<?php if (!empty($all_village_info)):
foreach ($all_village_info as $v_village) :
?>
<tr>
<td><?php echo $v_village->village_name ?></td>
<td><?php echo $v_village->zone_name ?></td>
<td><?php echo $v_village->school_name ?></td>
</tr>
<?php
endforeach;
?>
<?php endif; ?>
</tbody>
</table>
value in sql_is like
|-------------|------------|
|village_name |school_id |
|-------------|------------|
|Bhiwani |1,2,3 |
view is as
|-------------|------------|
|Village |School |
|-------------|------------|
|Bhiwani |School 1 |
i want to show like
|-------------|-------------------------------|
|Village |School |
|-------------|-------------------------------|
|Bhiwani |School 1, School 2, School 3 |
how can i do that ? help plz
how to read multiple value from joined table in codeigniter

You can use alias of the table and then select those
NOTE : I highly recommend you to use * if and only if your using all the columns else it will make your query bit slower.
/* You can take an alias for the table and select * from that, I have followed chaining method. */
$this->db
->select('v.*, s.*')
->from('tbl_village v')
->join('tbl_school s', 's.school_id = v.school_id', 'left')
->get()
->result_array();

You can try this solution for your problem :
Please change your modal function :
all_village_info:
public function all_village_info($id = NULL) {
$this->db->select('tbl_village.*', FALSE);
$this->db->select('GROUP_CONCAT(tbl_school.school_name ORDER BY tbl_school.school_id) as school_name', FALSE);
$this->db->from('tbl_village');
$this->db->join('tbl_school', 'FIND_IN_SET(tbl_school.school_id, tbl_village.school_id) > 0', 'left');
if (!empty($id)) {
$this->db->where('tbl_village.village_id', $id);
$query_result = $this->db->get();
$result = $query_result->row();
} else {
$query_result = $this->db->get();
$result = $query_result->result();
}
return $result;
}
I hope it will help you.

Related

Updating Table or div Data using Ajax Codeigniter

I am trying to create a page where it shows the current chats done by clients.
Now I am using Openfire as Server, and PHP Ajax for scripting.
Openfire dumps data into MySQL Table.
I retrive all the records using Codeigniter-PHP:
public function get_chats()
{
$this->db->select('*');
$this->db->from('ofMessageArchive');
$query = $this->db->get();
$result = $query->result();
$this->data['messages'] = $result;
$this->data['subview'] = 'dashboard/test';
$this->load->view('_layout_main', $this->data);
}
Now on my view I have table :
<table class="table table-striped table-bordered table-hover" >
<thead>
<th>From</th>
<th>To</th>
<th>Message</th>
<th>Time</th>
</thead>
<tbody>
<?php if(count($messages)): foreach($messages as $key => $message): ?>
<tr>
<td><?php $users = explode("__", $message->fromJID); echo $users[0];?></td>
<td><?php $tousers = explode("__", $message->toJID); echo $tousers[0]; ?></td>
<td><i class="material-icons">play_circle_filled</i>Message</td>
<td><?php echo $date->format('d-m-y H:i:s'); ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
Now I don't want to reload the whole page instead just refresh the table contents every 5 seconds.
I am using DataTables.
I also thought I could pass json to my view, but I don't know how to update it every 5 seconds.
public function get_chats()
{
$this->db->select('*');
$this->db->from('ofMessageArchive');
$query = $this->db->get();
$result = $query->result();
if (count($result)) {
$response = json_encode($result);
}
else
{
$response = false;
}
echo $response;
}
Also this is going to send new and older messages.
So I only want to append news messages to table old message should be not repeated
Your backend function :
public function get_chats()
{
$this->db->select('*');
$this->db->from('ofMessageArchive');
$query = $this->db->get();
$result = $query->result();
if (count($result)>0) {
$response['status']= true;
$response['messages']= $result;
$response['date']= date("d-m-y H:i:s", strtotime($your-date-here));
}
else
{
$response['status']=false;
}
echo json_encode($response);
}
You have to make javascript function like this :
<script>
function myAJAXfunction(){
$.ajax({
url:'your url here',
type:'GET',
dataType:'json',
success:function(response){
console.log(response);
var trHTML='';
if(response.status){
for(var i=0;i<response.messages.length;i++){
users =response.messages[i]fromJID.slice('--');
touser=response.messages[i]toJID.slice('--');
trHTML=trHTML+
'<tr>'+
'<td>'+users[0]+'</td>'+
'<td>'+touser[0]+'</td>'+
'<td><i class="material-icons">play_circle_filled</i>Message</td>'+
'<td>'+response.date+'</td>'+
</tr>';
}
$('tbody').empty();
$('tbody').append(trHTML);
}else{
trHTML='<tr><td colspan="4">NO DATA AVAILABLE</td></tr>';
$('tbody').empty();
$('tbody').append(trHTML);
}
},
error:function(err){
alert("ERROR LOADING DATA");
}
});
}
// calling above ajax function at every 5 seconds
setInterval(myAJAXfunction,5000);
</script>

Undefined variable,index error fetching data codeigniter

Im fetching data from a table to another table that will be shown in my dashboard page for a user after loggin in.
But there is a problem with the indexes, i got this error:
Here is the line error:
Here is my code:
My view file ("usuario"):
<thead>
<th>id</th>
<th>User</th>
<th>Subject</th>
<th>Grade</th>
<th>Date</th>
</thead>
<tbody>
<?php
if (count($records) > 0 && $records != false) {
foreach($records as $record) {
echo "<tr>
<td>".$record['id']."</td>
<td>".$record['User']."</td>
<td>".$record['name']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
</tr>";
}
}
?>
</tbody>
</body>
</html>
My controller file ("login"):
public function home(){
$data['record']=$this->m_login->getDetails();
$this->load->view('usuario',$data);
}
My model file ("m_login"):
public function getDetails()
{
$st=$this->db->SELECT('cursadas.*, usuarios.name as usuarios, materias.name as materias_name')->from('cursadas')
->join('usuarios','usuarios.id=cursadas.user_id')
->join('materias','materias.id=cursadas.subject_id')
->WHERE('cursadas.user_id=',$this->session->userdata['id'])
->get()->result_array();
return $st[0];
}
You have the variable $records on view but not on controller
Change
$data['record'] = $this->m_login->getDetails();
To
// add this array() just in case no results found
$data['records'] = array();
$data['records'] = $this->m_login->getDetails();
$this->load->view('usuario', $data);
Another way is on controller
$results = $this->m_login->getDetails();
$data['records'] = array();
if ($results) {
foreach ($results as $result) {
$data['records'][] = array(
'id' => $result['id'],
'User' => $result['User'],
'name' => $result['name'],
'grade' => $result['grade'],
'date' => $result['date']
);
}
}
$this->load->view('usuario',$data);
View
<?php if ($records) {?>
<?php foreach($records as $record) {?>
<tr>
<td><?php echo $record['id'];?></td>
<td><?php echo $record['User'];?></td>
<td><?php echo $record['name'];?></td>
<td><?php echo $record['grade'];?></td>
<td><?php echo $record['date'];?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>No Results Found</td>
</tr>
<?php } ?>
Wrong array index in your controller.
Change this
$data['record']=$this->m_login->getDetails();
to
$data['records']=$this->m_login->getDetails();
result_array() return returns result with array so you need to it like this -
if (count($record) > 0 && $record != false) {
foreach($record as $rec){
echo "<tr>
<td>".$rec['id']."</td>
<td>".$rec['User']."</td>
<td>".$rec['name']."</td>
<td>".$rec['grade']."</td>
<td>".$rec['date']."</td>
</tr>";
}
}
Please check this from above code and comment if you have any problem

codeigniter search with join table

this is my controller
function search_keyword()
{
$cari = $this->input->GET('cari');
$data['dapat'] = $this->order_test_m->search($cari);
$this->load->view('admin/a',$data);
}
this is my model
function search($cari)
{
$this->db->from("uhd_user_order AS t1");
$this->db->join("uhd_user_product_order AS t2", "t1.user_order_id = t2.user_order_id");
$this->db->where('user_order_reference',$cari);
$query = $this->db->get('uhd_user_order');
return $query->result();
}
this is my view
<tr>
<th>No.</th>
<th>Customer Name</th>
<th>Product Code</th>
<th>Payment Type</th>
<th>Delivery Date</th>
<th>Total Price</th>
<th style="text-align: center;padding-right: 15px;">Action</th>
</tr>
<?php if($dapat !== NULL) { ?>
<?php foreach ($dapat as $row => $test) {
?>
<tr>
<td><?= $test->user_order_id?></td>
<td><?= $test->sender_name?></td>
<td><?= $test->user_product_order_id?></td>
<td><?= $test->payment_type ?></td>
<td><?= $test->time.$test->date ?></td>
<td><?= $test->delivery_price?></td>
</tr>
<?php }
}else{
echo "<td colspan='3'>no customer for the result!</td>";
}
?>
</table>
guys i need help here
im new in codeigniter.
i need to make a search but the search result are needing 2 table from my database. time, date and user_product_order_id are from the uhd_user_product_order, and user_order_id, sender_name, payment_type, and user_order_reference(this the search key) are from uhd_user_order
in the view i can view it from my table uhd_user_order, but i cant view the time, date and the user_product_order_id
can you help me how to join the 2 table so i can see the best result from the search
Use this code on your model
public function search($cari){
$this->db->select('*');
$this->db->from("uhd_user_order AS t1");
$this->db->join("uhd_user_product_order AS t2", "t2.user_order_id = t1.user_order_id"); # confirm user_order_id in both table
$this->db->where('user_order_reference',$cari);
$query = $this->db->get();
return $query->result();
}
function search($cari)
{
$this->db->from("uhd_user_order AS t1");
$this->db->join("uhd_user_product_order AS t2", "t1.user_order_id = t2.user_order_id");
$this->db->where('user_order_reference',$cari);
$query = $this->db->get('uhd_user_order');
return $query->result();
}
become
function search($cari)
{
$this->db->join("uhd_user_product_order" , "uhd_user_order.user_order_id = uhd_user_product_order.user_order_id");
$this->db->where('user_order_reference',$cari);
$query = $this->db->get('uhd_user_order');
return $query->result();
}

Codeigniter query result row_array duplicate

I tried to get some records from database, like a ticket system, it's a code which downloading from database results
$this->db->select('*');
$this->db->from('tickets');
$this->db->where('t_author_steam_id', $steamid);
$query = $this->db->get();
if($query->num_rows() > 0) {
$row = $query->row_array();
return $row;
}
But it's duplicating results, and not showing all results, but only one.
there is result
Try this
Method 01
$this->db->select('*');
$this->db->from('tickets');
$this->db->where('t_author_steam_id', $steamid);
$query = $this->db->get();
$result = $query->result_array();
if(!empty($result)) # this will act as $query->num_rows() > 0
{
return $result;
}
Method 02
$this->db->select('*');
$this->db->from('tickets');
$this->db->where('t_author_steam_id', $steamid);
$this->db->group_by('t_author_steam_id'); # add this
$query = $this->db->get();
$result = $query->result_array();
if(!empty($result)) # this will act as $query->num_rows() > 0
{
return $result;
}
In view
<?php foreach($tickets as $items){ ?>
<tbody>
<th scope="row"><?php echo $items['t_id']; ?></th>
<th scope="row">
<?php if($items['t_lang'] == 1)
{
echo lang('polish');
} elseif($items['t_lang'] == 2) {
echo lang('english');
} ?>
</th>
<td><?php echo $items['t_title']; ?></td>
<td><?php echo $items['t_date']; ?></td>
<td>
<?php
if($items['t_status'] == 1)
{
echo '<span class="label label-info" id="status">'.lang('items-status-1').'</span>';
}
elseif($items['t_status'] == 2)
{
echo '<span class="label label-warning" id="status">'.lang('items-status-2').'</span>';
}
elseif($items['t_status'] == 3)
{
echo '<span class="label label-Success" id="status">'.lang('items-status-3').'</span>';
}?>
</td>
<td>Zobacz</td>
</tbody>
<?php } ?>
Method 1 is works fine. Problem is with in your code where you use foreach loop
$query->row_array() returns only the first row of all the records. If you want to return all records use $query->result_array() instead.

Too many queries, php. Creating lite forum engine

I've started to writing my engine of forum, just to refresh php skills.
My problem is that, when I make a board and one theard, I have double queries.
I know why, I have "foreach in different foreach" but I cannot find a way to sort it out, can you guys help me how would you do it? To avoid this big number of queries?
An example, SMF forum main page has only 12 queries (NO MATTER OF NUMBERS BOARDS AND THEARDS).
My page have 12 already, but I have only 2 categories, 5 boards, 4 theards, 1 user.
If I add one board, and one theard I have +2 queries.
<?php
if(!defined('USED'))
exit;
# Name of page!
$page = 'Forum';
$db = new Database();
$array = $db -> select("SELECT `id`,`name` FROM `".PREFIX."category`");
if(count($array) > 0)
{
$container .= '';
foreach($array as $category)
{
$container .= '<div class="panel panel-primary" id="category-'.$category['id'].'">
<div class="panel-heading">
<h3 class="panel-title">
'.$category['name'].'
</h3>
</div>
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="col-md-9">Board Name</th>
<th class="col-md-3">Latest</th>
</tr>
</thead>';
$array2 = $db -> select("SELECT `id`,`id_category`,`name`,`info` FROM `".PREFIX."boards` WHERE `id_category`=".$category['id']."");
if(count($array2) > 0)
{
foreach($array2 as $board)
{
$container .='<tbody>
<tr>
<td>
<strong>'.$board['name'].'</strong><br/>
<small>'.$board['info'].'</small>
</td>';
$array3 = $db -> select("SELECT `id`,`id_board`,`title`,`created_by`,`created_date` FROM `".PREFIX."theards` WHERE `id_board`=".$board['id']." ORDER BY `created_date` DESC LIMIT 1");
if(count($array3) > 0)
{
foreach($array3 as $theards)
{
$array4 = $db -> select("SELECT `id`,`name` FROM `".PREFIX."users` WHERE `id`=".$theards['created_by']."");
foreach($array4 as $user)
{
$created_by = $user['name'];
}
$container .='<td>
'.$theards['title'].'<br/><small>'.$created_by.', <abbr class="timeago" title="'.$theards['created_date'].'">less than a month ago</abbr></small>
</td>';
}
}
else
{
$container .= '<td>
Nothing is here!
</td>';
}
$container .=' </tr>
</tbody>';
}
}
else
{
$container .='<tbody>
<tr>
<td>Nothing is here!</td>
<td>...</td>
</tr>
</tbody>';
}
$container .='</table>
</div>';
}
}
else
{
Site::Error("You need to add a category first!");
}
And my select:
public function select($query) {
$rows = array();
$result = $this -> query($query);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
global $db_count;
$db_count = !isset($db_count) ? 1 : $db_count + 1;
return $rows;
}
Ive added $db_count at the end of the file to check numbers of queries.
Instead of running one query to get a list of IDs, then looping across those IDs to get another set of IDS, then looping across those IDs to get a set of data, how about writing one query, using a JOIN to line up the three tables?

Categories