While doing update i am getting following error
Severity: Notice Message: Undefined variable: user
This is my controller:
public function update_user_id($user_id) {
if($this->input->post('submit')){
$courses = array(
'user_name'=>$this->input->post('user_name'),
'email'=>$this->input->post('email')
);
$this->users_model->update_user($user_id,$users);
$base_url=base_url();
redirect("$base_url"."Dashboard/update_user_id/$user_id");
}
$result['user']=$this->users_model->user_id($user_id);
$this->load->view('edit_user',$result);
}
Which is my view
<?php echo form_open(base_url().'Admin/update_user_id/'.$user[0]->user_id);?>
User Name: <input type="text" name="user_name" value=" <?php echo $user[0]->user_name; ?>">
Email: <input type="text" name="email" value=" <?php echo $user[0]->user_name; ?>">
<?php echo form_close();?>
Don't know whats wrong with the code
Always follow documentation. By CI council convention, your class names should follow file names. I suppose you have that right. But you didn't follow demand for ucfirst() file and class names.
So in your case file shouldn't be named CoursesModel neither class should be named CoursesModel, but you should name your file and class Coursesmodel. Remember ucfirst() rule (regarding CI3+) for naming all classes wether controllers, models or libraries.
Also, if you load those files (models and libraries), for libraries always use strtolower() name while for models you can use both strtolower() and ucfirst() formatted name.
Personaly, I use to load libraries with strtolower while using to load models with ucfirst name and that way I make difference between those just having a quick look on code.
Try with:
Courses_m.php (This way I speed up parsing a little bit)
<?php defined('BASEPATH') or exit('Not your cup of tea.');
class Courses_m extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function update_course($course_id, $courses)
{
// your DB task --should return something
return true ?: false;
}
}
And in controller:
Courses_c.php (in APPPATH . 'config/routes.php' you can set what ever name you like for your route)
<?php defined('BASEPATH') or exit('Not your cup of tea.');
class Courses_c extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('form_validation');//just an library loading example
$this->load->model('Courses_m');//notice first capital here
}
public function update_course_id($course_id)
{
if($this->input->post('submit'))
{
$courses = array(
'course_name'=>$this->input->post('course_name'),
'no_of_hours'=>$this->input->post('no_of_hours')
);
// pay attention on capital first when you calling a model method
// need to be the same as in constructor where file is loaded
$this->Courses_m->update_course($course_id,$courses);
// you can use this way
redirect(base_url("Dashboard/update_course_id/$course_id"));
}
// use else block to avoid unwanted behavior
else
{
$result['course']=$this->Courses_m->course_id($course_id);
$this->load->view('edit_course',$result);
}
}
}
Related
I am trying to create a login process using codeigniter framework. Form validation is working but there is a problem in session. I can't fetch username after "Welcome-".
controller : Main.php
<?php
class Main extends CI_Controller
{
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run())
{
$username = $this->input->post('username');
$password= $this->input->post('password');
//model
$this->load->model('myModel');
if ($this->myModel->can_login($username,$password))
{
$session_data = array('username' => $username);
$this->session->set_userdata('$session_data');
redirect(base_url().'main/enter');
}
else
{
$this->session->set_flashdata('error','Invalid Username Or Password');
redirect(base_url().'main/login');
}
}
else
{
$this->login();
}
}
function enter()
{
if ($this->session->userdata('username')!=' ')
{
echo '<h2> Welcome- '.$this->session->userdata('username').'</h2>';
echo 'Logout';
}
else
{
redirect(base_url().'main/login');
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect(base_url().'main/login');
}
}
?>
Add session library in the constructor
<?php
class Main extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
$username = $this->session->userdata('username');
if (empty($username)) {
redirect('main/logout');
}
}
}
Another method you can load the session library in autoload.php file
File location: application/config/autoload.php
$autoload['libraries'] = array('database', 'email', 'session');
I suggest a slight code rearrangement for enter() that provides a better test for the user name using a tiny bit less code.
function enter()
{
if(empty($this->session->userdata('username')))
{
//base_url() accepts URI segments as a string.
redirect(base_url('main/login'));
}
// The following code will never execute if `redirect()` is called
// because `redirect()` does not return, it calls `exit` instead.
// So, you do not need an `else` block
echo '<h2> Welcome- '.$this->session->userdata('username').'</h2>';
echo 'Logout';
}
empty() will be true for an empty string, NULL, False and a couple of other things. In this case, you are most interested in an empty string or NULL. (empty() documentation HERE.)
You might want to consider adding 'trim' to your validation rules because it strips empty whitespace from the input string. That will remove the possibility of someone trying to input a username using only space characters.
Otherwise, your code should work. If it does not then it's very likely you do not have CodeIgniter sessions configured properly. There are many session setup questions answered here on Stack Overflow that will help you get it running.
I am new to laravel and following a tutorial for a basic app. So far the app has a default view layouts/default.blade.php, a partial _partials/errors.blade.php and three other views questions/index.blade.php, users/new.blade.php and users/login.blade.php
The routes are defined like so
// home get route
Route::get('/', array('as'=>'home', 'uses'=>'QuestionsController#get_index'));
//user register get route
Route::get('register', array('as'=>'register', 'uses'=>'usersController#get_new'));
// user login get route
Route::get('login', array('as'=>'login', 'uses'=>'usersController#get_login'));
//user register post route
Route::post('register', array('before'=>'csrf', 'uses'=>'usersController#post_create'));
// user login post route
Route::post('login', array('before'=>'csrf', 'uses'=>'usersController#post_login'));
questions/index.blade.php and users/new.blade.php load fine and within default.blade.php
when I call /login a blank page is loaded not even with default.blade.php. I am guessing that there is a problem in my blade syntax in login.blade.php given the fact that the default.blade.php works on the other routes and as far as I can see everything else is the same but if that was teh case wouldnt the default.blade.php route at least load?
the controller method this route is calling is as follows
<?php
Class UsersController extends BaseController {
public $restful = 'true';
protected $layout = 'layouts.default';
public function get_login()
{
return View::make('users.login')
->with('title', 'Make It Snappy Q&A - Login');
}
public function post_login()
{
$user = array(
'username'=>Input::get('username'),
'password'=>Input::get('password')
);
if (Auth::attempt($user)) {
return Redirect::Route('home')->with('message', 'You are logged in!');
} else {
return Redirect::Route('login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
}
?>
finally login.blade.php
#section('content')
<h1>Login</h1>
#include('_partials.errors')
{{ Form::open(array('route' => 'register', 'method' => 'POST')) }}
{{ Form::token() }}
<p>
{{ Form::label('username', 'Username') }}
{{ Form::text('username', Input::old('username')) }}
</p>
<p>
{{ Form::label('password', 'Password') }}
{{ Form::text('password') }}
</p>
<p>
{{ Form::submit('Login') }}
</p>
{{ Form::close()}}
#stop
You could also define the layout template directly from the Controller , this approach provides more flexibility , as the same View can be used with multiple layout templates .
<?php namespace App\Controllers ;
use View , BaseController ;
class RegisterController extends BaseController {
protected $layout = 'layouts.master';
public function getIndex()
{
// Do your stuff here
// --------- -------
// Now call the view
$this->layout->content = View::make('registration-form');
}
}
My example uses Namespaced Controller but the same concepts are applicable on non-Namespaced Controllers .
Notice : Our RegisterController extends Laravel's default BaseController , which makes a bit of preparation for us , see code below :
<?php
class BaseController extends Controller {
/**
* Setup the layout used by the controller.
*
* #return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
}
If a custom "Basecontroller" is defined , make sure that it also implements the "preparation" code .
I don't know what concepts are new to you , so let me make a couple arbitrary assumptions . If "namespace" and "Basecontroller" are << strange words >> , let me try to demystify these words .
Namespace : PHP's documentation is pretty well documented on this subject . My oversimplified explanation is as follows : Two skilled developers (JohnD and Irish1) decide to build their own PHP Logging Library and release the code as open source to the community .Most likely they will name their library "Log"
Now another developer would like to implement both libraries into his/her project (because JohnD's code uses MongoDB as storage medium while Irish1's code uses Redis ) . How would PHP's interpreter distinguishes the two code-bases from each other ? Simply prepend each library with a vendor name (JhonD/Log and Irish1/Log ) .
Basecontroller : Most likely your Controllers will share common functionality (a database connection , common before/after filters , a common template for a View ...... ) . It is a good practice not to define this "common functionality" into each Controller separately, but define a "Parent" Controller , from which all other Controllers will inherit its functionality . So later on , if you decide to make changes on the code , only one place should be edited .
My previous example uses " class RegisterController extends BaseController " , that BaseController is just checking if our (or any other) Child-controller has defined a property with the name of " $layout " , and if so , the View that it will instantiate will be encapsulated into that specified layout . See Laravel's flexibility , a group of Controllers share common functionality (by extending Basecontroller) but also are free to choose their own layout (if they desire to do so ) .
I have found my error
I did not have #extends('layouts.default') at the beginning of the login.blade.php template
I'm just wondering how I can use/define my own function using the $this->set() method in CakePHP? I want to do something like this...
AppController.php
<?php
function checkSetup() {
if ($this->Auth->user('setup') == 'notcomplete') { return true; }
}
$this->set('isSetup', checkSetup());
?>
And then I will be able to access and call it in my view file:
<?php if ($isSetup): ?>
You haven't setup your profile yet!
<?php endif; ?>
I've tried that, but It clearly doesn't work as I get a massive fatal error. Any ideas/suggestions on how I can do this?
$this->set('isSetup', checkSetup());
That line needs to be inside some function in order to be called. Presumably you want it in the beforFilter of your app controller - something like this:
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
function beforeFilter() {
$this->set('isSetup', checkSetup());
}
function checkSetup() {
if ($this->Auth->user('setup') == 'notcomplete') { return true; }
}
}
?>
i just created my own library on this folder (application/library) and following all steps to create individual library,
once i load this library in my controller it execute the function, but when trying to pass it to the view, nothing return
here is my code
MY OWN FUNCTION
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Common {
public function date_arabic()
{
$daysarabic=array('الأحد','الاثنين','الثلاثاء'
,'الأربعاء','الخميس','الجمعة','السبت');
$monarabic=array('','يناير','فبراير','مارس',
'أبريل','مايو','يونيو','يوليو'
,'أغسطس','سبتمبر','أكتوبر','نوفمبر','ديسمبر');
$date=getdate(time());
echo $daysarabic[$date['wday']].' '.$date['mday'].' '.$monarabic[$date['mon']].' '.$date['year']/*.' الوقت الأن '.$date['hours'].':'.$date['minutes'].':'.$date['seconds']*/;
}
}
MY Controller
//arabic date
$this->load->library('Common');
$this->common->date_arabic();
here it prints out the data in my own function, i tried to store this in a $data to pass it to the view like that
//arabic date
$this->load->library('Common');
$data['date_arabic'] = $this->common->date_arabic();
...
$this->load->view('home_page.php', $data);
then when going to view i just type
<?php echo $date_arabic ; ?>
but nothing returned
In your function, change the last line from this:
echo $daysarabic[$date['wday']].' '.$date['mday'].' '.$monarabic[$date['mon']].' '.$date['year']/*.' الوقت الأن '.$date['hours'].':'.$date['minutes'].':'.$date['seconds']*/;
to this:
return $daysarabic[$date['wday']].' '.$date['mday'].' '.$monarabic[$date['mon']].' '.$date['year']/*.' الوقت الأن '.$date['hours'].':'.$date['minutes'].':'.$date['seconds']*/;
when you are writing libraries, you have to manually grab the Codeigniter instance like this
$CI =& get_instance();
then you would use $CI where you would normally use $this to interact with loaded codeigniter resources
so...
instead of
$this->input->post();
you would write
$CI->input->post();
EXAMPLE LIBRARY STRUCTURE
class Examplelib {
// declare your CI instance class-wide private
private $CI;
public function __construct()
{
// get the CI instance and store it class wide
$this->CI =& get_instance();
}
public function lib_function()
{
// use it here
$this->CI->db->etc()
}
public function another_func()
{
// and here
$this->CI->input->post();
}
}
I failed to load a model from my controller
This is the controller file, article.php:
<?php
class Article extends CI_Controller {
function show($id) { //id'ye gore getir
$this->load->model('articles_model');
$parameter = $this->articles_model>getarticle($id);
$this->my_template->build('article_view', $parameter);
}
}
?>
This is the model file, articles_model.php:
<?php
class Articles_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function Getarticle($id) {
parent::Model();
$query = $this->db->get_where('articles', array('id' => $id));
$data['articles'] = $query->result();
return $data;
$query->free_result();
}
}
?>
just to add, i even tried to load it from autoloader, still no chance, i assume something is wrong with the model, or the whole system broke.
up: the models loads without problems, if i put echo in __construct function, it works, however, i cannot call the getarticle function. geez
UP: I did it! according to http://grasshopperpebbles.com/codeigniter/codeigniter-call-to-a-member-function-on-a-non-object/
i used
$CI =& get_instance();
and called the function
$CI->articles_model->getarticle($id) and it called the function
It should be,
$CI =&get_instance();
$CI->load->model('articles_model');
$parameter = $CI->articles_model>getarticle($id);
There's a parse error in the following line:
$parameter = $this->articles_model>getarticle($id);
It should be:
$parameter = $this->articles_model->getarticle($id);
Does that fix your problem? If not, what error message are you seeing?
Leif's answer is the right one. Just to add one thing: you don't have to use the long variable name like $this->articles_model over and over, by using the second parameter:
$this->load->model('articles_model','artm');
$parameter = $this->artm->getarticle($id);
Just a little faster to type, and can reduce typos like the one in your sample.