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});
Related
I try to pass the parameters from controller to url.
I try to achieve something like this: http://localhost/management_system/Job/search_job?keyword=word&location=location
for now i only get http://localhost/management_system/Job/search_job
Dose somebody know how i can achieve that?
Below you can see my controller:
public function search_job(){
if ($this->input->post('submit')) {
$location = $this->input->post('location', TRUE);
$keyword = $this->input->post('keyword', TRUE);
$data['all_jobs'] = $this->Job_model->search_job($keyword, $location);
if ($data['all_jobs'] > 0 ) {
$data['categoryes'] = $this->Job_model->get_category();
$this->autoload('job_list', 'eJobs', $data);
}
}else{
redirect('Job/jobs');
}
}
In your action you are waiting for a POST request but this: http://localhost/management_system/Job/search_job?keyword=word&location=location is a GET request.
If your request is this: http://localhost/management_system/Job/search_job?keyword=word&location=location
and you want to get location and keyword you must write code like this:
public function search_job() {
if ($this->input->post('submit')) {
$location = $this->input->get('location', TRUE);
$keyword = $this->input->get('keyword', TRUE);
$data['all_jobs'] = $this->Job_model->search_job($keyword, $location);
if ($data['all_jobs'] > 0 ) {
$data['categoryes'] = $this->Job_model->get_category();
$this->autoload('job_list', 'eJobs', $data);
}
} else {
redirect('Job/jobs');
}
}
You need to change
$this->input->post()
to
$this->input->get()
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();
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
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
I've got some sample code that I'd like to refactor as I need it to work after a record is saved. It currently works after the record is first rendered (using the afterFilter). What it does is render the view that I want with the layout and saves it to a file.
function afterFilter() {
parent::afterFilter();
if($this->params['pass'][0] == 'contact') {
$surrenderOuput = $this->surrender($this->params['pass'][0]);
$path = WWW_ROOT . 'cache' . DS . $this->params['pass'][0] . DS . 'index.html';
$file = new File($path, true);
$file->write($surrenderOuput);
$file->close();
}
}
function surrender($action = null, $layout = null, $file = null) {
$this->beforeRender();
$viewClass = $this->view;
if ($this->view != 'View') {
if (strpos($viewClass, '.') !== false) {
list($plugin, $viewClass) = explode('.', $viewClass);
}
$viewClass = $viewClass . 'View';
App::import('View', $this->view);
}
$this->Component->beforeRender($this);
$this->params['models'] = $this->modelNames;
if (Configure::read() > 2) {
$this->set('cakeDebug', $this);
}
$View =& new $viewClass($this);
if (!empty($this->modelNames)) {
$models = array();
foreach ($this->modelNames as $currentModel) {
if (isset($this->$currentModel) && is_a($this->$currentModel, 'Model')) {
$models[] = Inflector::underscore($currentModel);
}
$isValidModel = (
isset($this->$currentModel) && is_a($this->$currentModel, 'Model') &&
!empty($this->$currentModel->validationErrors)
);
if ($isValidModel) {
$View->validationErrors[Inflector::camelize($currentModel)] =&
$this->$currentModel->validationErrors;
}
}
$models = array_diff(ClassRegistry::keys(), $models);
foreach ($models as $currentModel) {
if (ClassRegistry::isKeySet($currentModel)) {
$currentObject =& ClassRegistry::getObject($currentModel);
if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
$View->validationErrors[Inflector::camelize($currentModel)] =&
$currentObject->validationErrors;
}
}
}
}
$this->autoRender = false;
$output = $View->render($action, $layout, $file);
return $output;
}
So I'm basically rendering the view with it's layout, and returning it as output, and saving it to a file. Great. Is there any way to do something similar in a model?
You may consider setting a member variable in your afterSave() in the model and checking that value in your afterFilter() in your controller.
I found this thread while searching for how to render a view from a model. In my case I'm calling a custom method in the model, so this might not work for afterSave(), but if you're calling a custom method you can do it like this:
Controller:
$this->Model->myFunc($this);
Model
public function myFunc($object) {
$object->render();
}
Hopefully that helps someone else who comes across this thread.