I have been developing using non framework for about 3 years and I have heard about PHP framework codeigniter.
I think I missed something using this framework which is used for API for my mobile application.
I've facing some problem to get data from database using Phil's CI framework, RESTful plugin. My browser shows error code:
{"status":false,"error":"Unknown method."}
Using my logic below:
controller: user.php
<?php
require(APPPATH.'libraries/REST_Controller.php');
class User extends REST_Controller{
public function user_get()
{
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
//CHECK TO MODEL FUNCTION
$user = $this->user_model->get_user($this->get('id'));
//IF USER EXIST
if($user)
{
$this->response($user, 200); // 200 being the HTTP response code
}
}
public function user_put()
{
// create a new user and respond with a status/errors
}
public function user_post()
{
// update an existing user and respond with a status/errors
}
public function user_delete()
{
// delete a user and respond with a status/errors
}
}
?>
model: user_model.php
<?php
class User_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_user($id){
$query = $this->db->get('mt_user', array('idmt_user'=>$id));
return $query->row_array();
}
}
?>
i'm accessing the database which is has this rows:
idmt_user,username,password, emails, createdate
accessed using mozilla:
#http://localhost/<project>/index.php/user/<userid>
Where's the error(s) ?
thanks.
update,
i am already defined the autoloads for database. But this problem still persist. Is there any helps? thanks
as stated below in answer, i tried to access the url, /user/get_user/ but still showing the same result. Is there any problem using idmt_user in database?
Insert in controllers:
function __construct() {
parent::__construct();
$this->load->model('user_model');
}
And try this route:
http://localhost//index.php/user/user/id/
I believe that the url you are accessing with is wrong.. Try accessing with the url #http://localhost/<project>/index.php/user/<method_name>/<user_id>
Another way of doing it would be using the URI Class.
Instead of writing the following:
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
Changed to:
$userid = $this->uri->segment(3);
Would be 3 based off the url being http://localhost/<project>/user/<method_name>/<user_id>
Reference for URI Class: http://www.codeigniter.com/user_guide/libraries/uri.html
In order to use $this->get(); there would have to be a query parameter to get. Example: id=
If you are passing query parameters than you could store these values in a array as shown below.
if(!empty($this->get()))
{
$params[] = $this->get();
}
I hope this helps.
You should to try include your model file into your controller file by using a __construct() function, like this:
function __construct(){
parent::__construct();
$this->load->model(array('user_model'));
}
Related
I'm still very new to this codeigniter. So i have a tables in my database called users table and t_lowongan table. The t_lowongan table have user_id field as a foreign key for the id_user in the users table. So when the user login and create a job posting, the user_id will be filled by the id_user from that user. I want to get the user data so that this user know which job posting that he has created by that user, but the data isn't showing, how can i fix it??
The Controller Lowongan :
public function lowongan()
{
$this_id = $this->session->userdata('id_user');
$data['t_lowongan'] = $this->db->get_where('t_lowongan', ['user_id', $this_id])->result();
$this->load-view('lowongan', $data);
}
Your approach to debugging isn't quite right here. Firstly, you must understand that the database object's result() method returns an array of row objects in the form of $row->field (or in your case, $row->user_id). On the other hand, the database object's result_array() method returns an array of arrays (in your case, $row['user_id']). Since you've used the former, I hope you've dealt with those row objects accordingly in the lowongan view which you then show. Failure to do so might result in the problem you've described in the question.
Assuming you've taken care of the view, the second thing to do then is to place an error_log() statement and see what value it's returning. You can place something like this just after the get_where() statement and then observe your HTTP server logs what value it's getting:
error_log("THE RESULT IS: " . print_r($data, true));
Depending on whether or not this is printing the correct value, you can then further troubleshoot where exactly the problem lies.
You must create controller and model and call model from construct
constroller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class LowonganController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model(array('m_lowongan'));
}
public function lowongan() {
$id = $this->session->userdata('id_user');
$data['t_lowongan'] = $this->m_lowongan->get_user_by_id($id);
$this->load-view('lowongan', $data);
}
}
model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_Lowongan extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function get_user_by_id($id)
{
$this->db->where('user_id', $id);
$query = $this->db->get('your_table_name');
return $query->row_array();
}
}
So what i did is that. I create a function called get_data on my model
The model :
public function get_data($where, $table){
return $this->db->get_where($table, $where);
}
And in the controller i just do this :
The Controller :
public function lowongan()
{
$this_id = $this->session->userdata('id_user');
$data['t_lowongan'] = $this->m_lowongan->get_data($where,'t_lowongan')->result();
$this->load-view('lowongan', $data);
}
And it works :D. But please let me know if this is like a wrong thing to do, Thank you :D
Try this
public function lowongan()
{
$this_id = $this->session->userdata('id_user');
$data['t_lowongan'] = $this->db->get_where('t_lowongan', ['user_id', $this_id])->row();
$this->load-view('lowongan', $data);
}
in your views
<?php print_r($t_lowongan)?>
I'm using https://github.com/chriskacerguis/codeigniter-restserver with codeigniter.
I'm trying to add a resource, and enable a get method with an id.
I added the Users controller which inherits the REST_Controller. I added a few methods, index_get, index_post. They both worked perfectly.
I then attempted to add an id parameter to the index_get function (so you can access a particular user- eg localhost/proj/Users/4 would you give you the user with id 4)
class Users extends REST_Controller {
public function index_get($id) {
echo $id;
}
public function index_post() {
echo "post";
}
}
I then tried, using postman, to access this get method:
localhost/proj/index.php/users/3 but it responded with:
{ "status": false, "error": "Unknown method" }
Any idea how I can fix this?
According to CodeIgniter Rest Server doc, you can access request parameter as below :
$this->get('blah'); // GET param
$this->post('blah'); // POST param
$this->put('blah'); // PUT param
So, Users class should be like that ..
class Api extends REST_Controller {
public function user_get() {
echo $this->get('id');
}
public function user_post() {
echo $this->post('id');
}
}
When you test with postman, you can request as below :
For get method,
http://localhost/proj/api/user?id=3
http://localhost/proj/api/user/id/3
For post method,
http://localhost/proj/api/user
form-data : [id : 2]
Hope, it will be useful for you.
I've such trouble and this solution worked for me.
For example, you have a controller file called Api.php like this:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Api extends RestController {
function __construct() {
parent::__construct();
}
function user_get($id) {
echo $id;
}
function user_put() {
}
function user_post() {
}
function user_delete() {
}
}
/* End of file Api.php */
/* Location: ./application/controllers/Api.php */
On the browser, you don't need to write http://localhost/api/user_get/1, instead, http://localhost/api/user/1, where 1 is [:id,] because the word _get, _put, _post, or _delete after the word user is the method. So, if you're using the get method, you should write your function in a class like this eg. user_get, users_get, students_get, etc.
Hope it can solve your issue.
i want to give access only to the authorized users
so i wrote the authentication code in the construct method
here is my code
class cp extends CI_Controller {
public function __construct(){
parent::__construct();
$this->this_mustbe_admin();
}
public function this_mustbe_admin()
{
$this->load->model('m_cp');
$md = $this->m_cp->is_admin();
if($md)
return $md;
else
{
redirect(base_url().'cp/login/');
}
}
function login()
{
$this->load->view('admin/login');
}
but i get error
The page isn't redirecting properly
if i remove this_mustbe_admin method from construct and put it on the other controllers it works fine
function do_stuff(){
$this->this_mustbe_admin();
// do stuff
}
but this way i have to write it in each and every one of my methods
You doing circular redirection. An imaginary stack trace:
http request to /cp/
__construct()
this->this_mustbe_admin() -> redirect to /cp/login
http request to /cp/login
__construct()
this->this_mustbe_admin() -> GOTO 3.
You will have to check what method you are trying to execute in your __construct before doing the redirection generating command.
if (!$this->router->method != 'login') {
$this->this_mustbe_admin();
}
Try to write like this
redirect('base_url(cp/login)');
i hope may it wrks....or simply give
redirect('cp/login');
because i got when i used like this
I have
login controller,model and view
url http://mySite/login
Now when i am at http://mySite/controller it shows the login form and then when i submit the form the run method is called so the url change to http://mySite/login/run
how can i stop this :?
P.S // I creat my own MVC following this tut : http://www.youtube.com/watch?v=2Eu0Nkpo6vM
login controller
class Login extends Conroller {
function __construct() {
parent::__construct();
}
function index()
{
$this->view->render('authentication/enter');
}
function run()
{
$this->model->run();
}
}
login model
class Login_Model extends Model
{
public function __construct()
{
parent::__construct();
}
public function run()
{
$sth = $this->dbh->connect()->prepare("SELECT UserID FROM users WHERE
username = :login ");
$sth->execute(array(':login' => $_POST['login']));
$data = $sth->fetch();
$count = $sth->rowCount();
if ($count > 0) {
// login
Session::set('loggedIn', $_POST['login']);
header('location: ../dashboard');
} else {
echo 4;
}
}
}
withour .htacces
the url is
http://mySite/index.php?url={controller name}
or
http://mySite/index.php?url={controller name}/{some method from the contoller}
Without watching that entire video or wondering too hard why you're re-inventing the PHP MVC wheel, here's my best guess.
Change your view's form to submit to the index action
<form method="post" action="login" ...
In your index action, detect a POST request and run the model's run() method from there
function index()
{
if ($this->request->isPost()) { // seriously, I'm just guessing here
$this->model->run();
}
$this->view->render('authentication/enter');
}
A couple of notes...
Don't do controller tasks (ie redirecting) from the model
Always exit; after sending a Location response header
Drop this mess and try a proven and tested MVC framework like Symfony or Zend
I'm trying to create user profiles for my site where the URL is something like
mysite.com/user/ChrisSalij
Currently my controller looks like so:
<?php
class User extends Controller {
function user(){
parent::Controller();
}
function index(){
$data['username'] = $this->uri->segment(2);
if($data['username'] == FALSE) {
/*load default profile page*/
} else {
/*access the database and get info for $data['username']*/
/*Load profile page with said info*/
}//End of Else
}//End of function
}//End of Class
?>
At the moment I'm getting a 404 error whenever i go to;
mysite.com/user/ChrisSalij
I think this is because it is expecting there to be a method called ChrisSalij.
Though I'm sure I'm misusing the $this->uri->segment(); command too
Any help would be appreciated.
Thanks
It's because the controller is looking for a function called ChrisSalij.
A few ways to solve this:
change
function index(){
$data['username'] = $this->uri->segment(2);
to be
function index($username){
$data['username'] = $username;
and use the URL of mysite.com/user/index/ChrisSalij
if you don't like the idea of the index being in the URL you could change the function to be called a profile or the like, or look into using routing
and use something along the lines of
$route['user/(:any)'] = "user/index/$1";
to correctly map the URL of mysite.com/user/ChrisSalij