Retrieve related post with codeigniter - php

I'm unable to retrieve similar post data from db with codeigniter. In my blog, I have a tags field which is keeping data like 'php,mysql,mongo,java,jquery'
I just try to get similar post which is related with current posts tags. But im not getting expected result. and the problem is in my query. Its show only three post and that is 1st, last, and number 3rd one.
[CONTROLLER]
public function showpost()
{
$data = array();
$this->load->view('header',$data);
$data['post'] = $query->result();
$data['similar'] = $this->crudModel->getSimilarPost();
$this->load->view('showfull',$data);
$this->load->view('footer');
}
[MODEL]
public function getSimilarPost()
{
$query = $this->db->get_where('blogs',array('id' => $this->uri->segment(3)));
foreach($query->result() as $row){ $tags = $row->tags; }
$match = explode(',', $tags);
for($i = 0; $i < count($match); $i++)
{
$this->db->like('tags',$match[$i]);
$this->db->from('blogs');
$sqlQuery = $this->db->get();
}
return $sqlQuery->result();
}
[VIEW]
foreach($similar as $row)
{
echo($row->btitle.'<br/>');
}

Try this.
public function showpost()
{
$data = array();
$this->load->view('header',$data);
$data['post'] = $query->result(); // why this line??
$data['similar'] = $this->crudModel->getSimilarPost();
$this->load->view('showfull',$data);
$this->load->view('footer');
}
[MODEL]
public function getSimilarPost()
{
$query = $this->db->get_where('blogs',array('id' => $this->uri->segment(3)));
foreach($query->result() as $row){ $tags = $row->tags }
$match = explode(',', $tags);
$result = [];
for($i = 0; $i < count($match); $i++)
{
$this->db->like('tags',$match[$i]);
$this->db->from('blogs');
$sqlQuery = $this->db->get();
if($sqlQuery->num_rows()>0)
$result[] = $sqlQuery->result();
}
return $result;
}
[VIEW]
$check = [];
foreach($similar as $row)
{
foreach($row as $data)
{
if(!in_array($data->btitle,$check))
{
$check[] = $data->btitle;
echo $data->btitle.'<br/>';
}
}
}

Related

How to filter products by size in codeigniter

I am filtering products by size, i selected all the li's user has selected
using this jquery function :
var arr_size = [];
i = 0;
$(".filtersize li a").each(function(e) {
if ($(this).hasClass("selected-filter")) {
arr_size[i++]= $(this).text();
}
});
this is working fine, but i am passing this array from ajax to codeigniter controller and i am saving size data as comma separated value in database :
size column:
'S','M','L','XL'
and javascript array also contains comma seperated value for eg. if user has selected two values it will contain S,M i am not able to search array values in db using like function is there any other function or method to achieve this my code is as follows:
var data = {id:pid,arr_s:arr_size};
var url = "<?php echo base_url()?>controlle/viewproducts";
var result = post_ajax(url, data);
controller:
public function viewproducts()
{
$id=$this->input->post('id');
$size_arr=$this->input->post('arr_s');
$result['product'] = $this->product_m->get_product_size_filter($id,$size_arr);
$this->load->view('product_filter_view/view_product',$result);
}
Model:
public function get_product_size_filter($id,$size) {
$where_query = '';
$size_array = explode(',', $size);
foreach ($size_array as $size_item) {
$size = "$size_item";
$where_query .= "dg_products.size LIKE '%$size%' OR ";
}
$where_query = rtrim($where_query, " OR ");
$this->db->select('dg_products.*, AVG(dg_rating.rating) As averageRating');
$this->db->from('dg_products');
$this->db->join('dg_rating', 'dg_products.id = dg_rating.product_id','left');
$this->db->where('dg_products.category_id',$id);
$this->db->where($where_query);
$this->db->group_by("dg_products.id");
$query = $this->db->get();
$result = $query->result();
return $result;
}
I think, you can convert your size string to array and run query.
Below example code:
public function viewproducts()
{
$id = $this->input->post('id', true);
$size_string = $this->input->post('arr_s', true);
$size_array = explode(',', $size_string);
$result['product'] = array();
foreach ($size_array as $size_item) {
$size = "'$size_item'";
$result['product'][] = $this->product_m->get_product_size_filter($id, $size);
}
$this->load->view('product_filter_view/view_product', $result);
}
If you don't want run multi db queries, you can use:
public function viewproducts()
{
$id = $this->input->post('id', true);
$sizes = $this->input->post('arr_s', true);
$result['product'] = $this->product_m->get_product_size_filter($id, $sizes);
$this->load->view('product_filter_view/view_product', $result);
}
Here is model:
public function get_product_size_filter($id, $size)
{
$where_query = '';
$size_array = explode(',', $size);
foreach ($size_array as $size_item) {
$size = "'$size_item'";
$where_query .= "size LIKE '%$size%' OR ";
}
$where_query = rtrim($where_query, " OR ");
$this->db->select('*');
$this->db->from('dg_products');
$this->db->where($where_query);
$query = $this->db->get();
return $query->result();
}
UPDATED
public function get_product_size_filter($id,$size)
{
$where_query = '';
$size_array = explode(',', $size);
foreach ($size_array as $size_item) {
$size = "$size_item";
$where_query .= "dg_products.size LIKE '%$size%' OR ";
}
$where_query = rtrim($where_query, " OR ");
$this->db->select('dg_products.*, AVG(dg_rating.rating) As averageRating');
$this->db->from('dg_products');
$this->db->join('dg_rating', 'dg_products.id = dg_rating.product_id','left');
$this->db->where('dg_products.category_id',$id);
$this->db->where("($where_query)");
$this->db->group_by("dg_products.id");
$query = $this->db->get();
$result = $query->result();
return $result;
}

How to sort array of objects in php [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 years ago.
I have an array like below,
[{
"name":"Daniel",
"connection_status":"1"
},
{
"name":"Danny",
"connection_status":"3"
},
{
"name":"Moris",
"connection_status":"2"
},
{
"name":"Manny",
"connection_status":"1"
}]
I want to sort my array by status like 1,2,3 in this order.
This is my code,
public function getProfileDataForMySociety($user_id)
{
$this->db->select('*');
$this->db->from('profile');
$this->db->where('profile_id!=', $user_id);
$query = $this->db->get();
$list = $query->result();
$friends = $this->checkFriends($list, $user_id);
return $friends;
}
public function checkFriends($list, $user_id)
{
$array = [];
foreach ($list as $k => $v) {
// print_r(json_encode($list));
$friends = $this->checkStatus($v->profile_id);
//print_r($friends);
$relationship = '';
$relation_id = '';
foreach ($friends as $kk => $vv) {
if ($user_id == $vv->sent_id) {
if ($vv->status == 1) {
$relationship = 1;
}
if ($vv->status == 2) {
$relationship = 2;
}
} else if ($user_id == $vv->recieved_id) {
// pending
if ($vv->status == 1) {
$relationship = 3;
$relation_id = $vv->sent_id;
}
if ($vv->status == 2) {
$relationship = 4;
}
}
}
$list[$k]->connection_status = $relationship;
$list[$k]->relation_id = $relation_id;
}
return $list;
}
public function checkStatus($id)
{
$this->db->select('*');
$this->db->from('requests');
$this->db->where('sent_id', $id);
$this->db->or_where('recieved_id', $id);
$query = $this->db->get();
$list = $query->result();
return $list;
}
connection status is not a db field.
Where $list is my o/p array.Can anyone help me.Thanks in advance.
I want to sort my array based on my connection_status.
if i understand you correctly this may help you
public function getProfileDataForMySociety($user_id)
{
$this->db->select('*');
$this->db->from('profile');
$this->db->where('profile_id!=', $user_id);
$this->db->order_by('status', 'asc');
$query = $this->db->get();
$list = $query->result();
return $list;
}
You can apply order by in query
public function getProfileDataForMySociety($user_id)
{
$this->db->select('*');
$this->db->from('profile');
$this->db->where('profile_id!=', $user_id);
$this->db->order_by('status'); // USE ORDER BY
$query = $this->db->get();
$list = $query->result();
return $list;
}
public function getProfileDataForMySociety($user_id)
{
$this->db->select('*');
$this->db->from('profile');
$this->db->where('profile_id!=', $user_id);
$query = $this->db->order('status asc')->get();
$list = $query->result();
return $list;
}

Get database through email id in codeigniter

Controller[In Article Page Article Properly work with pagination, store user email id in 'articles' database , now i tried to get the user firstname, and lastname from users table but not work properly ]
public function articles()
{
$data['title'] = "Articles";
$config = array();
$config["base_url"] = base_url() . "sd/articles/";
$config["total_rows"] = $this->model_users->record_count_articles();
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model_users->fetch_result_articles($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
if ($this->session->userdata ('is_logged_in')){
$data['profile']=$this->model_users->profilefetch();
$this->load->view('sd/header',$data);
$this->load->view('sd/articles', $data);
$this->load->view('sd/footer', $data);
} else {
$this->load->view('sd/sdheader', $data);
$this->load->view('sd/articles', $data);
$this->load->view('sd/sdfooter', $data);
}
}
Model [ Get Users Name in Article Page ]
public function record_count_articles() {
return $this->db->where('status','1')->count_all("articles");
}
public function fetch_result_articles($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->where('status','1')->order_by('id', 'DESC')->get("articles");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Add These Lines [ But Not Work]
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
$query = $this->db->select('firstname')->select('lastname')->where('email',$data[0]->email)->get("users");
$data['name_info']=$query->result_array();
}
return $data;
}
return false;
You have 2 problem here. please have a look on comments in code.
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
//1) $data[0]->email keep repeating same email.
// inner $query variable should be different.
$innerQuery = $this->db->select('firstname,lastname')->where('email',$row->email)->get("users");
//2) you need to store query result on array.
// $data['name_info'] stores only single record.
$data[]=$innerQuery ->result_array();
}
return $data;
}
return false;
You should avoid query in loop if you can achieve it by join
EDIT: Lets try this with join
public function fetch_result_articles($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db
->join('users u','u.email = a.email','left')
->where('a.status','1')->order_by('a.id', 'DESC')->get("articles a");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
I have not tested the code. but it is better way than loop.

CodeIgniter View Blog Post Page

Hello guys i am trying to create a blog. The first home page is ok.. i am getting the shrot description and the categories from the database but...i have problems with the links:
this are my controller functions:
public function index()
{
$this->load->model('Model_cats');
$data['posts'] = $this->Model_cats->getLivePosts(10);
$data['cats'] = $this->Model_cats->getTopCategories();
$data['title'] = 'Welcome to Paul Harbuz Blog Spot!';
$data['main'] = 'public_home';
$this->load->vars($data);
$this->load->view('template', $data);
}
public function category($id)
{
$data['category'] = $this->Model_cats->getCategory($id);
$data['posts'] = $this->Model_cats->getAllPostsByCategory($id);
$data['cats'] = $this->Model_cats->getTopCategories();
$data['title'] = $data['category']['name'];
$data['main'] = 'public_home';
$this->load->vars($data);
$this->load->view('template', $data);
}
public function post($id)
{
$data['post'] = $this->Model_cats->getPost($id);
$data['comments'] = $this->Model_cats->getComments($id);
$data['cats'] = $this->Model_cats->getTopCategories();
$data['title'] = $data['post']['title'];
$data['main'] = 'public_post';
$this->load->vars($data);
$this->load->view('template');
}
this are my model function:
function getTopCategories()
{
$this->db->where('parentid',0);
$query = $this->db->get('categories');
$data = array();
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$data[$row['id']] = $row['name'];
}
}
$query->free_result();
return $data;
}
function getLivePosts($limit)
{
$data = array();
$this->db->limit($limit);
$this->db->where('status', 'published');
$this->db->order_by('pubdate', 'desc');
$query = $this->db->get('posts');
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
}
function getCategory($id)
{
$data = array();
$this->db->where('id',$id);
$this->db->limit(1);
$query = $this->db->get('categories');
if($query->num_rows() > 0)
{
$data = $query->row_array();
}
$query->free_result();
return $data;
}
function getAllPostsByCategory($catid)
{
$data = array();
$this->db->where('category_id', $catid);
$this->db->where('status', 'published');
$query = $this->db->get('posts');
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
function getPost($id)
{
$data = array();
$this->db->where('id',$id);
$this->db->limit(1);
$query = $this->db->get('posts');
if ($query->num_rows() > 0)
{
$data = $query->row_array();
}
$query->free_result();
return $data;
}
and in the view page i have something like this:
if ( count($posts) )
{
foreach ($posts as $key => $list)
{
echo '<h2>'.$list['title'].'</h2>';
echo auto_typography(word_limiter($list['body'], 200));
echo anchor('post/'.$list['id'],'read more >>');
}
echo '<br/><br/>';
}
I'm getting the post id in the url but.. i don't know why the page is not found.
You have to add the controller name to the anchor uri segments.
echo anchor('CONTROLLER/post/'.$list['id'],'read more >>');
More on this topic in the CodeIgniter URLs documentation.
If you want a URL like http://example.com/post/123 then you have to add the following to your application/config/routes.php file:
$route['post/(:num)'] = "CONTROLLER/post/$1";
More on routing is also available in the documentation.

CodeIgniter Pagination Problem

Helo. I’m trying to make a items pagination. I have 3 function, first displaying category, 2nd displaying sucategory. 3rd displaying items is cold get_books_by_subcategory. 3rd function get a segment->url(3) argumnet, i want to make a pagination in the same function. but i cant do it.
This is functions code in controller:
function get_category()
{
$query = $this->Kategorie_model->get_category();
$this->response['podkategorie'] = '';
$this->response['kategorie'] = '';
$podkategorie = '';
if($query->num_rows() > 0)
{
foreach($query->result() as $item)
{
$podkategorie = $this->get_sub_category($item->CAT_ID);
$this->response['kategorie'] .= $this->load->view('Ksiegarnia/left', array('kategorie' =>$item, 'podkategorie'=>$podkategorie), true);
}
}
$data = $this->response['kategorie'];
return $data;
}
function get_sub_category($id)
{
$this->response['wynik'] = '';
$query = $this->Kategorie_model->get_sub_category($id);
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$link = site_url('ksiegarnia/get_books_by_subcategory/'.$row->SUBC_ID);
$this->response['wynik'] .= '<div class="subcat_name">'.$row->SUBC_Name.'</div>';
}
}
else
{
$this->response['wynik'] = '<H1>BRAK DANYCH </H1>';
}
return $this->response['wynik'];
}
function get_books_by_subcategory()
{
$widok['center'] = '';
$widok['left'] = $this->get_category();
$widok['right'] = $this->load->view('Ksiegarnia/right', '', true);
$id = $this->uri->segment(3);
if(isset($id) and is_numeric($id))
{
$query = $this->Kategorie_model->get_books_by_subcategory($id, $this->uri->segment(4));
if($query->num_rows() > 0)
{
foreach($query->result() as $item)
{
$widok['center'] .= $this->load->view('Ksiegarnia/get_books', array('data' =>$item), true);
}
}
else
{
$widok['center'] = $this->load->view('Ksiegarnia/get_books', array('tytul' =>'<h1>brak danych</h1>'), true);;
}
$widok['center'] .= $this->pagination->create_links();
$this->load->view('Ksiegarnia/index', $widok);
}
}
And this is my model:
function get_books_by_subcategory($id, $offset=0)
{
$config['base_url'] = 'http://lukaszbielecki.cba.pl/ksiegarnia/CI/index.php/ksiegarnia/get_books_by_subcategory/'.$id;
$config['per_page'] = 7;
$this->db->where('SUB_CATEGORY_SUBC_ID', $id);
$config['total_rows'] = $this->db->get('books')->num_rows();
$config['num_links'] = 20;
$this->pagination->initialize($config);
return $this->db->get('books',$config['per_page'],$offset);
//$wynik = $this->db->query("Select * from books where SUB_CATEGORY_SUBC_ID = '".$id."'");
//return $wynik;
}
The arguments in url is changing, but dispalyin only a items from first subcategory.
Help, please.
On this line $widok['center'] = $this->load->view('Ksiegarnia/get_books', array('tytul' =>'<h1>brak danych</h1>'), true);; in your controller, you have an additional semicolon ; that is causing a syntax error.

Categories