i am currently learning CI and i have come to an issue that i cant seem to solve.
i set up my wamp server in a drive and inside the www(root) folder i have extracted the codeigniter files.
![example][1][1]: http://i.stack.imgur.com/7RKqG.png
then I created my php files for view/model and controller and set the default route in the config/routes.php
so now when I go to my browser and type localhost I get the post.php displayed without anyissue.
but I am unable to access any of the views from here. for example i have a new_post.php view and when i type in the address bar localhost/new_post.php i get a "Not Found
The requested URL /new_post.php was not found on this server." error.
what am i doing wrong? below i have posted the code which i have written in the post.php controller along with a image of the file structure/names i have.
posts.php - controller
<?php
class Posts extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('post'); //loads the post model u created in the models folder
}
function index() //goes to this function 1st when u access the controller
{
$data['posts']=$this->post->get_posts(); // load all the data from the get_posts function in post model to the data array posts
$this->load->view('post_index', $data); //loads the view
}
function post($postID)
{
$data['post']=$this->post->get_post($postID);
$this->load->view('post', $data);
}
function new_post()
{
if($_POST)
{
$data=array(
'title'=> $_POST['title'],
'post'=> $_POST['post'],
'active' =>1
);
$this->post->insert_post($data);
redirect(base_url(). 'posts/');
}
else
{
$this->load->view('new_post');
}
}
function editpost($postID)
{
$data['success']=0;
if($_POST)
{
$data_post=array(
'title'=> $_POST['title'],
'post'=> $_POST['post'],
'active' => 1
);
$this->post->update_post($postID,$data);
$data['success'] =1;
}
$data['post']=$this->post->get_post($postID);
$this->load->view('edit_post',$data);
}
function deletepost($postID)
{
$this->post->delete_post($postID);
redirect(base_url(). 'posts/');
}
}
![structure][1] [1]: http://i.stack.imgur.com/SnsbW.png
In CodeIgniter you have to use controller to get access to his function
you are saying "when i type in the address bar localhost/new_post.php i get a Not Found" because you try to direct access its function name you have to use example.com/controllername/functionname like this
http://localhost/posts/new_post
for more information check codeignier url
https://ellislab.com/codeigniter/user-guide/general/urls.html
if you not removed index.php using .htaccess then you have to use your url like this
http://localhost/index.php/posts/new_post
In CodeIgniter, everything runs through the main "index.php" file, in your root directory.
So, you would access your new post page, like this;
http://localhost/index.php/posts/new_post
Have a read through the CodeIgniter user guide, it will answer any problem you have.
https://ellislab.com/codeigniter/user-guide/
Related
I am trying to configure pretty URLs in codeigniter and it's not making much sense to me. I'd like my URLs to follow the following structure;
example.com/admin/view/form/123
I can successfully view data when I visit the URL above. I see the same data when I visit;
example.com/admin/view/123
Notice the 3rd segment /form/ is missing, but still returns the data. It's almost like it's ignoring this - I thought CI should throw a 404 error, or do I need to check for this manually? If so, how?
When I visit this URL;
example.com/admin/view
I see the following error;
An uncaught Exception was encountered
Type: ArgumentCountError
Message: Too few arguments to function Admin::view(), 0 passed
My code can be seen below;
Controller
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->load->model('Admin_model');
}
public function index()
{
$this->load->view('template/header');
$data = array(
'title' => 'Admin Page'
);
$this->load->view('admin/index', $data);
$this->load->view('template/footer');
}
public function view($form_submission_id)
{
$this->load->view('template/header');
$data = array(
'title' => 'Form View Page',
'record' => $this->Admin_model->getSubmissionById($form_submission_id)
);
$this->load->view('admin/view/index', $data);
$this->load->view('template/footer');
}
}
Model
class Admin_model extends CI_Model {
public function getSubmissionById($form_submission_id) {
$this->db->select('*');
$this->db->from('submissions');
$this->db->where('id', $form_submission_id);
$query = $this->db->get();
return $query->row();
}
}
Routes
// redirect any urls that contain a number after /form
$route['admin/view/form/(:num)'] = "admin/view/$1";
My views folder structure looks like this;
- views
-- admin
- index.php
- view
-- index.php
Ideally I want my URLs to look like this, and throw 404 errors where they don't.
example.com/admin/view/form/123
example.com/admin/update/form/123
example.com/admin/delete/form/123
You can do this by several ways.
The fastest way is by creating routes like this:
$route['admin/view/form/(:num)'] = "Admin/view/$1";
When typing exemple.com/admin/view/form/9 , it will redirect to the controller admin, function view and the "9" will be the parameter $form_submission_id
The same thing for routes below.
$route['admin/update/form/(:num)'] = "Admin/update/$1";
$route['admin/delete/form/(:num)'] = "Admin/delete/$1";
of course you could create a function for each one, view, update, delete ... etc
It's normal that you see error when you enter example.com/admin/view because the view function take 1 parameter $form_submission_id
I have something like website.com/profile/nameofuser that is working.
But if I have website.com/profile/_nameofuser I get 404 error also website.com/profile/nameofuser_ or website.com/profile/nameof_user is working. It's not something related to accepted characters, but what's the problem?
class Profile extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->model('Profile_model');
$this->load->helper(array('url', 'form', 'htmlpurifier'));
}
public function index() {
$this->load->library('form_validation');
if(getUserData($this->uri->segment(2), "ID") < 0) {
$this->session->set_flashdata('error', 'Profil inexistent.');
redirect(base_url());
}
if (!is_cache_valid(md5('profile' . $this->uri->segment(2) . ''), 300)){
$this->db->cache_delete('profile', $this->uri->segment(2));
}
if(getUserData($this->uri->segment(2), "ID") > 0) {
/* some mysql queries.. */
}
$data["main_content"] = 'profile/profile_view';
$this->load->view('includes/template.php', $data);
} else {
$this->session->set_flashdata('error', 'Profil inexistent.');
redirect(base_url());
}
}
function _remap($method,$args)
{
if (method_exists($this, $method))
{
$this->$method($args);
}
else
{
$this->index($method,$args);
}
}
}
Here is my profile controller. I really don't know what's the problem. If I enter an invalid profile redirects with error flashdata so ti's ok. Maybe it's a remap problem?
1) Check the fie format in your view file.. if it is html file that mean you cannot call it without its format
for example
if your file is php format have name home-view.php
you can call it as
$this->load->view('home-view');
but if it is html file then the name in home-view.html
so you have to call it with its exstention as
$this->load->view('home-view.html');
your call to /profile/nameofuser is missing a fundamental from the MVC architecture.
You need to call a controller/method combination (in CI, your basic url is domain.com/controller/method)...
since you don't have a specific method for each user within the profile controller, which is actually a good thing, you need a method within the controller that handles your users. You already have it, it's called index
If you point your URL to /profile/index/nameofuser and change $this->uri->segment(2) to $this->uri->segment(3) you should get it to work
give it a try and let me know
I have a login script, and when the login is successful I want it to redirect them to the home page(welcome_message.php) for some reason it does not link me to this file, instead throws a 404 and says "The requested URL "http://localhost/musiclear/index.php/views/welcome_message" cannot be found or is not available. Please check the spelling or try again later."
I am using CodeIgniters redirect() function for the change.
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if ($query) { // if users credentials validated
$data = array('usernames' => $this->input->post('username'),
'is_logged_in' => true);
$this->session->set_userdata($data); //set session data
redirect('welcome_message'); //redirect to home page
} else { //incorrect username or password
$this->index();
}
}
Try passing the full URI to the redirect function like so:
redirect(base_url('views/welcome_message'));
Assuming of course that your controller is Views and page (function) is welcome_message
You can't redirect browser to view file directly, but You can redirect it to controller, which will show Your view. In Your example You're trying to access CodeIgniter's (which based in musiclear folder on Your localhost) Controller with name views and call welcome_message() method from it. But if Your really want to show it You must have next structure:
musiclear/
Application
Controllers
views.php
and views.php content:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Views extends CI_Controller {
function index() {
// default action, required method
}
function welcome_message(){
$this->load->view('welcome_message');
}
}
?>
actually when you make redirects in CodeIgniters it looks up for your controller and you should load view through the function of controller. e.g:
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if ($query) { // if users credentials validated
$data = array('usernames' => $this->input->post('username'),
'is_logged_in' => true);
$this->session->set_userdata($data); //set session data
redirect(base_url().'home/welcome'); //redirect to home function
} else { //incorrect username or password
$this->index();
}
}
function welcome(){
$this->load->view('welcome_mesage');
}
May be you forgot that redirect() function work only for controller class ie.
let you have welcomeclass so you can redirect it by using
redirect('wolcome');
you also redirect a function of controller class
if you want to redirect to page function of welcome controller class so you will writr
redirect('welcome/page');
I have this controller: Resales, and I am in the Administrator controller and need to create a new Resale.. how should I do that?
first option:
Administrator form calls /resales/addResales
second option: Administrator has a method addResale that loads the Resale model and inserts it.
What should I do?
thanks
Administrator controller shouldn't be loading the Resales controller - that should be a model that both controllers use. You should load your Resales model into the Administrator controller in the $uses = array() property at the top of your controller file:
class AdministratorController extends AppController {
var $uses = array('Resale', //the rest of your models);
public function createResale() {
$this->Resale->create();
$this->Resale->set($this->data['Resale']);
$this->Resale->save();
}
}
Other options are that you could use Ajax to post the request for you, or you could use $this->requestAction() in your Administrator controller to use a processing function in your Resales controller:
// administrator controller
public function createResale() {
// define your data here
$result = $this->requestAction('resales/create', array($data_array));
}
Have a look at the manual for more information on requestAction:
http://book.cakephp.org/2.0/en/controllers.html
EDIT
You've just asked about views. In this case, there's no real need to create a view for createResale(), what you might want to do instead is set a Session flash message, then redirect back to your form. You will need to ensure you've included the Session helper at the top of your controller:
class AdministratorController extends AppController {
var $helpers = array('Session', // any others here);
Then you prevent the layout and render of views, do your thing and set a session flash with the results message:
public function createResale() {
// don't render a view or layout
$this->layout = '';
$this->render(false);
// process your request
$result = // do stuff... return true or false for result
$msg = $result ? 'Added successfully!' : 'Error adding resale!';
// set flash message
$this->Session->setFlash($msg);
// return to that form
$this->redirect(array('action' => 'formYouCameFrom'));
}
Now on your form, you'll simply do this:
echo $this->Session->flash();
... which will output the results.
I am pretty new to codeigniter. I do know php.
How can I accomplish to load the right view?
My url: /blog/this-is-my-title
I’ve told the controller something like
if end($this->uri->segment_array()) does exist in DB then load this data into some view.
I am getting an 404-error everytime I access /blog/whatever
What am i seeing wrong?
unless you're using routing, the url /blog/this-is-my-title will always 404 because CI is looking for a method called this-is-my-title, which of course doesn't exist.
A quick fix is to put your post display code in to another function and edit the URLs to access posts from say: /blog/view/the-post-title
A route like:
$route['blog/(:any)'] = "blog/view/$1";
may also achieve what you want, if you want the URI to stay as just `/blog/this-is-my-title'
The may be more possibilities:
The most common - mod_rewrite is not active
.htaccess is not configured correctly (if u didn't edited it try /blog/index.php/whatever)
The controller does not exist or is placed in the wrong folder
Suggestion: if you only need to change data use another view in the same controller
if (something)
{
$this->load->view('whatever');
}
else
{
$this->load->view('somethingelse');
}
If none of those works post a sample of code and configuration of .htaccess and I'll take a look.
The best way to solve this problem is to remap the controller. That way, you can still use the same controller to do other things too.
No routing required!
enter code here
<?php
class Blog extends Controller {
function __construct()
{
parent::__construct();
}
public function _remap($method, $params = array())
{
if (method_exists($this, $method))
{
$this->$method();
}
else
{
$this->show_post();
}
}
function index()
{
// show blog front page
echo 'blog';
}
function edit()
{
// edit blog entry
}
function category()
{
// list entries for this category
}
function show_post()
{
$url_title = $this->uri->segment(2);
// get the post by the url_title
if(NO RESULTS)
{
show_404();
}
else
{
// show post
}
}
}
?>