How to count post view in codeigniter blog - php

I am new in codeigniter and php.
I want to count post view number and store it database.
That means, I want to create a popular post plugin by counting post view.
But i can't do this.
Please anyone help me. Tell the way.
Here is my article Controller..
public function __construct(){
parent::__construct();
$this->load->model('article_m');
}
public function index($category_slug, $id, $slug=NULL){
// Fetch the article
$this->db->where('pubdate <=', date('Y-m-d'));
$this->data['article'] = $this->article_m->get($id);
$this->data['articles'] = $this->article_m->get();
// Return 404 if not found
count($this->data['article']) || show_404(uri_string());
if ($this->uri->segment(1) !== $this->data['cat']->category_slug) {
echo "Hi There, This is wrong";
}
$this->load->view('templates/article', $this->data);
}
}
Here is my Models:
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
Sorry for my bad english..

$post_id = "???"
if(isset($_COOKIE['read_articles'])) {
//grab the JSON encoded data from the cookie and decode into PHP Array
$read_articles = json_decode($_COOKIE['read_articles'], true);
if(isset($read_articles[$post_id]) AND $read_articles[$post_id] == 1) {
//this post has already been read
} else {
//increment the post view count by 1 using update queries
$read_articles[$post_id] = 1;
//set the cookie again with the new article ID set to 1
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}
} else {
//hasn't read an article in 24 hours?
//increment the post view count
$read_articles = Array();
$read_articles[$post_id] = 1;
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}

star complex to do?
//function single post, query get by slug and id post
if(!isset($_SESSION['views'. $id]) || (isset($_SESSION['views'. $id]) && $_SESSION['views'. $id] != $id)){
$this->post_m->viewer($id); //load model viewer
$this->session->set_userdata('views'. $id, $id);
}
// Model "post_m"
function viewer($id)
{
$this->db->where('id', $id);
$this->db->set('views', 'views+1', FALSE);
$this->db->update('posts'); //table update
}
$id is id post

Related

CodeIgniter - Checking to see if a slug already exists in the database

I Have made a function add_items. and I Want if the slug already exists in the database then the form_validation runs and shows the error message. and that's work fine if the slug exists. But the main problem is that if I want to insert the new Data in the database which obviously has a different slug then the data is not inserted.
public function add_items()
{
if($this->input->post()){
if($this->input->is_ajax_request()){
$title = $this->input->post('title');
$url_title = url_title($title);
$this->form_validation->set_rules($url_title,'callback_slug_exists');
if($this->form_validation->run() == FALSE)
{
echo "FAIL::Slug Already Exist::error";
return;
}
$item_price = $this->input->post('item_price');
$item_description = $this->input->post('item_description');
$insertData = array('item_title' =>$title,'item_url'=>$url_title,'item_price' =>$item_price,'item_description'=>$item_description,
'big_pic' =>$image_path."/".$image);
$result = $this->common_model->insert_record('store_items',$insertData);
if($result){
echo "OK::Record Inserted Successfully::success";
return;
}
else {
echo "FAIL::Record Insertion Failled::success";
return;
}
}
}
$this->show('admin/add_items.php');
}
Here are The function slug_exists()
function slug_exists($slug)
{
$this->common_model->slug_exists($slug);
}
This is in Model
function slug_exists($slug)
{
$this->db->where('item_url',$slug);
$query = $this->db->get('store_items');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
This is the insert_record()
function insert_record($tbl, $data)
{
$this->db->insert($tbl, $data);
return $this->db->insert_id();
}
And this is DB Structure
try this:you can post data direct in an array. no need define it.
$insertArray=array(
item_title' =>$this->input->post('title'),
'item_url'=>$this->input->post('url_title'),
'item_price' =>$this->input->post('item_price'),
'item_description'=>$this->input->post('item_description'),
'big_pic' =>$image_path."/".$image);
$this->db->insert('store_items', $insertArray);
Try like this
function slug_exists($slug)
{
$this->db->where('item_url',$slug);
$query = $this->db->get('store_items');
if ($query->num_rows() > 0){
return false;
}
else{
return true;
}
}
If slug already exists then you need to fail the validation to get the error so return false on existing
Also, return the answer/result to a callback function
function slug_exists($slug)
{
return $this->common_model->slug_exists($slug);
}
Update
Controller
if($this->form_validation->run() == FALSE){
echo "FAIL::Slug Already Exist::error";
return;
}else{
$item_price = $this->input->post('item_price');
$item_description = $this->input->post('item_description');
$insertData = array('item_title' =>$title,'item_url'=>$url_title,'item_price' =>$item_price,'item_description'=>$item_description,
'big_pic' =>$image_path."/".$image);
$result = $this->common_model->insert_record('store_items',$insertData);
if($result){
echo "OK::Record Inserted Successfully::success";
return;
}
else {
echo "FAIL::Record Insertion Failled::success";
return;
}
}

connect two different database in one laravel 5.5

I want to minimize this by removing if else statement using simple code in laravel 5.5 can someone help me with it?
public function shirts($type='')
{
if($type == 'glass') {
$shirt = Product::where('category_id','1')->get();
$products = Category::find(1);
} elseif ($type == 'ic') {
$shirt = Product::where('category_id','2')->get();
$products = Category::find(2);
} elseif ($type == 'cover') {
$shirt = Product::where('category_id','3')->get();
$products = Category::findOrFail(3);
} else {
$shirt = Product::all();
}
return view('front.shirt',compact('products','shirt'));
}
One way would be to create a mappings for your type and comparing the type with the mappings.
public function shirts($type = '')
{
$type_mappings = [
'glass' => 1,
'ic' => 2,
'cover' => 3
];
if(array_key_exists($type, $type_mappings)) {
$shirt = Product::where('category_id', $type_mappings[$type])->get();
$products = Category::find($type_mappings[$type]);
} else {
$shirt = Product::all();
$products = null;
}
return view('front.shirt', compact('products', 'shirt'));
}
Edit : i assumed you want to avoid if else not as what the title of question says if still i am unclear please add comment so i can update the answer Thanks!
Lets handle it somewhere else as i guess your function only has the responsibility to find product based on id it get not mapping part so we can have something like :
// Your function with single responsibility to return product.
public function shirts($category = '')
{
$type = $this->CategoryIdMapper($category);
if($type == 0) {
$shirt = Product::all();
$products = null;
} else{
$shirt = Product::where('category_id',$type_id)->get();
$products = Category::findOrFail($type_id);
}
return view('front.shirt',compact('products','shirt'));
}
//let the mapping part be done by some independent function which you can later modify accordingly and independently.
public function CategoryIdMapper($category)
{
$categories = ['glass'=>1, 'ic'=> 2, 'cover' => 3 ];
if(array_key_exist($category,$categories))
{
return $categories[$category];
}
return 0;
}

Codeigniter: Call to a member function result_array() on a non-object caused by bad column?

I'm having an issue in codeigniter to return a result set. When I'm avoiding 1 column in my select, the result is correct.
But when i want to include the column (description) then i get the error and my result-set is corrupt. Anyone knows how to solve this issue. The column has soms records with characters like &,'/... I might think that this causes the problem.
some details:
'char_set' => 'UTF-8',
'dbcollat' => 'Latin1_General_100_CS_AS',
I already tried to change these parameters without success.
EDIT Code added:
get and get_by function.
public function get($id = NULL, $single = FALSE) {
if($id != NULL){
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE){
$method = 'row';
}
else{
$method = 'result';
}
if($_order_by != ''){
if(!count($this->db->ar_orderby)){
$this->db->order_by($this->_order_by);
}
}
//$query = $this->db->query("Select Description from items WHERE Company = 'MINITFR'");
// $array = $query->result_array();
// return 'test';
// var_dump($this->db->get_compiled_select($this->_table_name));
return $this->db->get($this->_table_name)->result_array();
// return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE) {
$this->db->where($where);
return $this->get(NULL,$single);
}
function in controller:
public function show_items(){
$this->load->model('item_m');
$this->data['ajax_req'] = TRUE;
$where = "Company = '".$this->session->userdata('company')."'";
$this->data['item_list'] = $this->item_m->get_by($where,FALSE);
$this->load->view('pages/details/components/item_list', $this->data);
}
use this one:
return $this->db->get('table_name')->result_array();

how to use slug in codeigniter

i don't know how to make url like this
tkd/index.php/article/77/Kejurnas-2013
i am getting error with url like this
tkd/index.php/article/77/Kejurnas%202013
this is my controller
public function index($id = null, $slug = FALSE){
// Fetch the article
$this->db->where('pubdate <=', date('Y-m-d'));
$this->data['article'] = $this->mberita->get_by_id($id,$slug);
//echo '<pre>' . $this->db->last_query() . '</pre>';
// dump($this->data['article']);
// Return 404 if not found
count($this->data['article']) || show_404(uri_string());
// Redirect if slug was incorrect
$requested_slug = $this->uri->segment(3);
$set_slug = $this->data['article']->slug;
if ($requested_slug != $set_slug) {
redirect('article/' . $this->data['article']->id . '/' . $this->data['article']->slug, 'location', '301');
}
// Load view
/*add_meta_title($this->data['article']->judul_berita);*/
$this->data['contents'] = 'article';
$this->load->view('template/wrapper/mahasiswa/wrapper_article', $this->data);
}
and this is my modal
public function get_by_id($id = 0, $slug = FALSE)
{
if ($id === 0 && $slug === FALSE)
{
$query = $this->db->get('$this->tbl_berita');
return $query->result_array();
}
return $this->db->get_where($this->tbl_berita, array('id' => $id, 'slug' => $slug),1)->row();
}
please help me how to make the right url. thank you
You can use one of CodeIgniters helper functions url_title()
Takes a string as input and creates a human-friendly URL string. This
is useful if, for example, you have a blog in which you'd like to use
the title of your entries in the URL.
site_url("articles/{ID}/").url_title({TITLE});

Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database

Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database.
in my view :
<label>Trimestres :</label>
<div class="controls" >
<?php $options = array(
'trim1' => ' Premier trimestre (Janv,Fév,Mars)',
'trim2' => ' Deuxiéme trimestre (Avril,Mai,Juin)',
'trim3' => ' Troisiéme trimestre (Juill,Aout,Sept)',
'trim4' => ' Quatriéme trimestre (Oct,Nov,Déc)',
);
echo form_multiselect('trimestres', $options , $this->input->post('trimestres') ? $this->input->post('trimestres') : $participant_sport->trimestres, 'id="trim"'); ?>
</div>
</div>
in my controller :
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
The function array_from_post() is defined on application\core\MY_Model.php :
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
in my model :
public function get_new()
{
$participant_sport = new stdClass();
$participant_sport->matricule = '';
$participant_sport->nom = '';
$participant_sport->prenom = '';
$participant_sport->beneficiaire = '';
$participant_sport->sexe = '';
$participant_sport->telephone = '';
$participant_sport->date_naissance = '';
$participant_sport->date_inscription_sport = '';
$participant_sport->trimestres = '';
$participant_sport->sport_montant_paye = '';
$participant_sport->sport_debut_periode = '';
$participant_sport->sport_fin_periode = '';
return $participant_sport;
}
Any help Please? i think that must be an array but i don't know how to do it?
i thing that i must do something like that :
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
to insert more than one option selected in one row but i don't know how to do it in codeigniter
the get() function :
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
If select name (in HTML tag) is trimestres it will always remember last selection. Use trimestres[] as a name to get array with all selected values`
<select name="trimestres[]" multiple …
By the way:
I don't know how array_from_post() works but it has to change trimestres[] values to one string to save all of them in one column. It is hard to search/add/delete one value if all values are in one string. It is "SQL Antipattern". You could do another table in database for trimestres - one value in one row.
Edit:
It will change all arrays into string with elements connected by ,. Not tested.
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
// print_r($this->input->post($field));
if( is_array( $this->input->post($field) ) ) {
$data[$field] = join(",", $this->input->post($field));
} else {
$data[$field] = $this->input->post($field);
}
// print_r($data[$field]);
}
return $data;
}
Edit:
Not tested.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
// explode to array
// print_r($this->data['participant_sport']->trimestres); // test before explode
// $this->data['participant_sport']['trimestres'] = explode(",", $this->data['participant_sport']['trimestres']);
$this->data['participant_sport']->trimestres = explode(",", $this->data['participant_sport']->trimestres);
// print_r($this->data['participant_sport']->trimestres); // test after explode
} else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// rest of code
}
There is a easy way to solve this problem that I found today.
you have to serialize the $_POST['trimestres'] array just after array_form_post .
the this array will save to database as a serialize string.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$data['trimestres'] = serialize($_POST['trimestres']);
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
When you just need this data back form database just use php unserialize() function .
Hope it will help to do this easily ....
-thanks

Categories