Why adding $this->models. make it faster? - php

I was playing around with this code. http://programmersvoice.com/tag/code
And I noticed that the following line.
$this->load->model($this->models."pagemodel", 'pages');
I compare this with
$this->load->model("pagemodel", 'pages');
This is what codeigniter's document http://codeigniter.com/user_guide/general/models.html#loading suggest.
However method 2 takes longer time than the first one.
Could anyone explain what "$this->models." do please?
Thanks in advance.
The following is the whole code of pages.php in controllers/admin
<?php
class Pages extends Application
{
function Pages()
{
parent::Application();
$this->auth->restrict('editor'); // restrict this controller to editor and above
$this->load->model($this->models."pagemodel", 'pages'); // Load the page model
}
function manage()
{
$data = $this->pages->pages(); // List the pages
$this->table->set_heading('Title', 'Slug', 'Actions'); // Setting headings for the table
foreach($data as $value => $key)
{
$actions = anchor("admin/pages/edit/".$key['id']."/", "Edit") . anchor("admin/pages/delete/".$key['id']."/", "Delete"); // Build actions links
$this->table->add_row($key['title'], $key['slug'], $actions); // Adding row to table
}
$this->auth->view('pages/manage'); // Load the view
}
function delete($id)
{
$this->pages->delete($id);
$this->auth->view('pages/delete_success');
}
function add()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Page Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() == FALSE)
{
$this->auth->view('pages/add');
}
else
{
$data['title'] = set_value('title');
$data['content'] = set_value('content');
$data['slug'] = url_title($data['title'], 'underscore', TRUE);
$this->pages->add($data);
$this->auth->view('pages/add_success');
}
}
function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Page Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() == FALSE)
{
$data = $this->pages->page($id);
$this->auth->view('pages/edit', $data[0]);
}
else
{
$data['title'] = set_value('title');
$data['content'] = set_value('content');
$data['slug'] = url_title($data['title'], 'underscore', TRUE);
$this->pages->edit($id, $data);
$this->auth->view('pages/edit_success');
}
}
}
?>

I'm not totally sure about the following, since the current version of Codeigniter doesn't seem to populate the $this->models variable, but I think that:
$this->models contained the full path to the application models directory, and therefore loading is faster, since CI doesn't have to look in different folders (global & application)

Related

Add user on Codeigniter 3

Hi i am new here and i dont know how to use codeigniter and now im confused. So i am currently trying to add user data to the database using codeigniter 3.1.10 . When i click the " save " button there's nothing to display. The page was refresh
Can you help me please?
Models:
function add_user($data) {
$this->db->set("username",$data["username"]);
$this->db->set("password",$data["password"]);
$this->db->set("indirizzo",$data["indirizzo"]);
$this->db->set("citta",$data["citta"]);
$this->db->set("cap",$data["cap"]);
$this->db->insert("user");
$ins_id =$this->db->insert_id();
return $ins_id;
}
Controllers:
function add() {
$this->load->library('form_validation');
$this->form_validation->set_rules('save', '', 'trim|required|number');
if ($this->form_validation->run()) :
$data = array(
"username"=>$this->input->post("username"),
"password"=>$this->input->post("password"),
"indirizzo"=>$this->input->post("indirizzo"),
"citta"=>$this->input->post("citta"),
"cap"=>$this->input->post("cap"),
);
$user_id= $this->user_model->add_user($data);
$this->log_model->scrivi_log($user_id,"user","add");
$this->session->set_flashdata('feedback', 'User added.');
redirect("user/pageuser/".$user_id);
else :
$content = $this->view->load("content");
$content->load("clienti_form","user/add");
$this->view->render();
endif;
}
Your doing a lot wrong, starting from the fact that your doing stuff from the model in your controller, and you should divide it, otherwise your not using the concept of MVC.
Try something like this, being hard to help you, without seeing the whole code:
Model
function add_user()
{
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'indirizzo' => $this->input->post('indirizzo'),
'citta' => $this->input->post('citta'),
'cap' => $this->input->post('cap')
);
return $this->db->insert('user', $data);
}
Controller
function add() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('indirizzo', 'Indirizzo', 'required');
$this->form_validation->set_rules('citta', 'Citta', 'required');
$this->form_validation->set_rules('cap', 'Cap', 'required');
$errore = true;
if ($this->form_validation->run() === FALSE){ // if doesnt work load your view
$this->load->view('your view');
}
else {
$this->user_model->add_user();
$this->log_model->scrivi_log($user_id,"user","add");
$this->session->set_flashdata('feedback', 'User added.');
redirect("user/pageuser/".$user_id);
$content = $this->view->load("content");
$content->load("clienti_form","user/add");
$this->view->render();
}
}
You really should try and search more about it, and learn!
I could learn a lot of the basics of CodeIgniter, watching this channel that has great content, and explains every detail: https://www.youtube.com/playlist?list=PLillGF-RfqbaP_71rOyChhjeK1swokUIS
function add_user($data) {
$this->db->insert("user",$data);
$ins_id =$this->db->insert_id();
return $ins_id;
}
use this in model..
and in controller set rules for each like this
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
// for all other

CodeIgniter Redirection from form input

I've never used a PHP framework, but I wanted to learn how to use one so I could more easily program for my company, so I chose CodeIgniter.
I am following the code igniter tutorial for a news section so I could learn how things work - but I am having some issues/questions.
Now, I am to the point in the tutorial that I have a form that submits and takes me to a success page. In normal PHP this is where I would just redirect the page to the view page of the news item submitted. In CodeIgniter I have a view function in my controller here
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
I'm not sure how to get the slug from the form when it is submitted.
Here is my create function (Basically the one that inserts the database info and redirects to news/success)
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
But I want this to redirect to the view page. To do that I need to have the slug I believe. So it should redirect to news/view/$slug - but I'm not sure how to do this.
My set_news model:
public function set_news()
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
You should use something like that:
redirect('news/view/'.url_title($this->input->post('title'), 'dash', TRUE));

validation error in Codeigniter

May I know why my insert function will display the validation message first even i do not insert any data yet.once I enter the insert page,it display the validation message.i have try to move the form validation to the below of the if else statement,it do not show the validation message but it cannot submit the data to the database. below is my controller function.
public function Insert_Result($Course_ID=null)
{
$this-load-helper('form');
$this-load-library('form_validation');
/* Model */
$this-load-model('ResultEvaluation');
/* Session */
$session_data = $this-session-userdata('logged_in');
$data['Ins_ID'] = $session_data['Ins_ID'];
$this-session-set_userdata($data);
/* Form Validation*/
//$this-form_validation-set_rules('Course_ID', 'Course_ID', 'required');
$this-form_validation-set_rules('Matric_No', 'Matric_No','required');
$this-form_validation-set_rules('Student_Name', 'Student_Name', 'required');
$this-form_validation-set_rules('Result_Mark_1', 'Result_Mark_1', 'required');
$this-form_validation-set_rules('Result_Mark_2', 'Result_Mark_2', 'required');
$this-form_validation-set_rules('Result_Mark_3', 'Result_Mark_3', 'required');
$this-form_validation-set_rules('Result_Mark_4', 'Result_Mark_4', 'required');
$this-form_validation-set_rules('Result_Mark_5', 'Result_Mark_5', 'required');
if ($this-form_validation-run() === FALSE)
{
$data['results'] = $this-ResultEvaluation-get_record();
$data['query'] = $this-ResultEvaluation-view($Course_ID);
$this-load-view('templates/header');
$this-load-view('Insert_Result', $data);
$this-load-view('templates/footer');
}
else
{
$my_action = $this-input-post('submit');
if ($my_action == 'Submit')
{
$this-ResultEvaluation-insert_record($Course_ID);
redirect('Result_Evaluation/Student_Result_List/'.$Course_ID,
'refresh');
}
}
$my_action = $this-input-post('submit');
if ($my_action == 'Cancel')
{
redirect('Result_Evaluation/Student_Result_List/'.$Course_ID,
'refresh');
}
}
I think this should help
public function index(){
$this->load->library(array('form_validation'));
$this->form_validation->set_rules('field_name', 'Text','trim|required');
if($this->form_validation->run()==TRUE){
// do something
}else{
// validation error
redirect("to/your/controller");
break;
}
}
for more information visit : http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

creating news item in codeigniter

i want to create news item in codeigniter with use slug but is error display like this.
> Call to a member function insert() on a non-object in line 34
I am a newbie in Codeigniter and couldn't really figure out how to solve this.
my controller
function tambah_profil()
{
$this->data['title'] ='create a new items';
$this->form_validation->set_rules('judul', 'Judul', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->data['contents'] = $this->load->view('admin/profil/tambah_profil', '', true);
}else{
$this->mhalaman->insert_profil();
$this->data['contents'] = $this->load->view('admin/profil/view_profil', '', true);
}
$this->data['orang'] = $this->mlogin->dataPengguna($this->session->userdata('username'));
$this->data['contents'] = $this->load->view('admin/profil/tambah_profil', '', true);
//$this->data['contents'] = 'admin/profil/tambah_profil';
$this->load->view('template/wrapper/admin/wrapper_ukm',$this->data);
}
my model
var $db;
private $tbl_halaman = 'halaman';
public function __construct()
{
parent ::__construct();
$this->load->database();
}
function get_profil($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get($this->tbl_halaman);
return $query->result_array();
}
$query = $this->db->get_where($this->tbl_halaman, array('slug'=>$slug));
return $query->row_array();
}
function insert_profil()
{
$slug = url_title($this->input->post('judul'),'dash', TRUE);
$data = array(
'judul' => $this->input->post('judul'),
'slug' => $slug,
'content' => $this->input->post('content')
);
return $this->db->insert($this->tbl_halaman ,$data); //line 34
}
please help me what to do. thank you.
Please check whether you have loaded $this->load->database() inside the model constructor.
$this->db->method_name(); will only work when the database library is loaded.
If you plan to use the database throughout your application, I would suggest adding it to your autoload.php in /application/config/.
$autoload['libraries']=array('database');

codeigniter CMS form validation

Firstly Im new to CodeIgniter and MVC.
I am Creating a CMS and coudln't decide which route to take with do I have two applications (front end/CMS) or just create the admin as a controller. I opted for one application and creating the admin via a Controller.
Doing it this way I have ran into a problem with form validation where if it doesn't validate I cant load the form I have to redirect which then means it wont repopulate the unvalidated fields. I use a variable in the 3rd URI segment to determine whether to display a form for inserting a new record, a populated form for editing a record, or a tabled list of all records.
The form posts to /admin/videos/save
function videos()
{
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else {
$this->load->model('videos_model');
$data['section'] = "Videos";
$data['area'] = "Videos";
$data['mode'] = $this->uri->segment(3, 'create');
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
if ($data['mode'] == 'edit') {
$data['ID'] = $this->uri->segment(4);
$data['videos'] = $this->videos_model->get_videos($data['ID']);
} elseif ($data['mode'] == 'list') {
if ($this->uri->segment(4)) {
$data['filter'] = $this->uri->segment(4);
$data['videos'] = $this->videos_model->get_filtered_videos($data['filter']);
} else {
$data['videos'] = $this->videos_model->get_filtered_videos();
}
} elseif ($data['mode'] == 'save') {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('videoTitle', 'Title', 'required');
$this->form_validation->set_rules('Code', 'Youtube Code', 'required');
if ($this->form_validation->run() === FALSE) {
redirect('/admin/videos');
} else {
$this->videos_model->set_videos();
redirect('/admin/videos/list');
}
}
if ($data['mode'] != "create" && empty($data['videos'])) {
show_404();
}
$this->load->view('admin/templates/head', $data);
$this->load->view('admin/templates/body_navbar', $data);
$this->load->view('admin/videos', $data);
$this->load->view('admin/templates/footer', $data);
}
}
Am I setting about this the wrong way, Should I use two application folders or have 3 controllers for editing/inserting/viewing all. Or is there a solution to my current setup?
I personally haven't used CodeIgniter's form helper nor validation lib, so excuse my ignorance, but is there any particular reason you're not doing this as AJAX post instead?
Am I setting about this the wrong way, Should I use two application
folders or have 3 controllers for editing/inserting/viewing all. Or is
there a solution to my current setup?
Why 3 controllers? You can have a single controller with multiple functions. Honestly, I'd recommend just doing a simple AJAX post on your form and returning some JSON data whether validation passed or not -- no need for redirects.
Something like:
// AJAX
function validateForm() {
$.post('route/to/controller', {"apple": appleValue, "peach": peachValue}, function(data) {
json = $.parseJSON(data);
if (json.success)
alert('Great!');
else
alert('Nope!');
});
//Controller
function validateForm()
{
$data['success'] = ...validation checks...
echo json_encode($data);
}
I have continued to use my one application folder and the entire admin as a controller.
I have solved my form validation and repopulating issue by continuing to redirect back to the form but storing the form fields and errors in a session.
I destroy the error data in the session once viewed but leave the other info intact which allows the user to navigate away and come back and the info will remain. Once the form is validated correctly and information stored in the database it destroys the session data.
function videos()
{
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else {
$this->load->model('videos_model');
$data['section'] = "Videos";
$data['area'] = "Videos";
$data['mode'] = $this->uri->segment(3, 'create');
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
if ($this->session->userdata('videoTitle'))
$data['videoTitle'] = $this->session->userdata('videoTitle');
if ($this->session->userdata('Code'))
$data['Code'] = $this->session->userdata('Code');
if ($this->session->userdata('videoTitle'))
$data['description'] = $this->session->userdata('description');
if ($this->session->userdata('errors')){
$data['errors'] = $this->session->userdata('errors');
$this->session->unset_userdata('errors');
}
if ($data['mode'] == 'edit') {
$data['ID'] = $this->uri->segment(4);
$video_data = $this->videos_model->get_videos($data['ID']);
$data['videoTitle'] = $video_data['videoTitle'];
$data['Code'] = $video_data['blipCode'];
$data['description'] = $video_data['description'];
} elseif ($data['mode'] == 'list') {
if ($this->uri->segment(4)) {
$data['filter'] = $this->uri->segment(4);
$data['videos'] = $this->videos_model->get_filtered_videos($data['filter']);
} else {
$data['videos'] = $this->videos_model->get_filtered_videos();
}
} elseif ($data['mode'] == 'save') {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('videoTitle', 'Title', 'required');
$this->form_validation->set_rules('Code', 'Youtube Code', 'required');
if ($this->form_validation->run() === FALSE) {
$formdata = array(
'videoTitle' => $this->input->post('videoTitle'),
'Code' => $this->input->post('Code'),
'description' => $this->input->post('description'),
'errors' => validation_errors()
);
$this->session->set_userdata($formdata);
redirect('/admin/videos');
} else {
$this->videos_model->set_videos();
$this->session->unset_userdata('videoTitle');
$this->session->unset_userdata('Code');
$this->session->unset_userdata('description');
redirect('/admin/videos/list');
}
}
$this->load->view('admin/templates/head', $data);
$this->load->view('admin/templates/body_navbar', $data);
$this->load->view('admin/videos', $data);
$this->load->view('admin/templates/footer', $data);
}
}

Categories