Redirect where no profile data in database - php

Controller
function view_profil(){
$id = $this->session->userdata('idtabelX');
$profil[''] = $this->class_model->function_model($id);
$this->load->view('view_profil', $profil);
}
Model
function function_model($id){
$this->db->select('*');
$this->db->from('tabelA a');
$this->db->join('tabelB b','b.idtabelB=a.ididtabelB');
$this->db->join('tabelC c','c.idtabelC=a.idtabelC');
$this->db->where('idtabelX', $id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
}
}
If the profile is clicked, it will show the data user profile stored in database, but if the user does not have the data profile in database, I want to redirect the user to a insert page to populate the profile data.
Thank you very much for help me to resolve this problem.

In your controller -
function view_profil(){
$id = $this->session->userdata('idtabelX');
$profil[''] = $this->class_model->function_model($id);
//add this bit of code
if($profil[''] == NULL)
{
redirect('your_controller/your_add_method');
}
else
{
$this->load->view('view_profil', $profil);
}
}
You need to use the redirect() function and pass the url of your controller method for insertion as parameters.

Related

Puzzle with PHP using codeigniter

I have a problem using codeigniter, now I have a system that show you a question in a page called start, the question comes random from the database using this code.
$data['question'] = $this->Setting->Loop('challenges_questions', 'ORDER BY RAND() LIMIT 1');
then check the form_validation
if($this->form_validation->run() === TRUE){
foreach($data['question']->result() as $ques){
$query = $this->Challenges_Model->addAnswer($ques->the_answer);
}
}
this is the model
public function addAnswer($answer){
if($this->input->post('answer') == $answer){
if(!$this->session->userdata('is_stopped')){
$this->db->query("UPDATE challenges_scores SET points = points+1 WHERE user_id = ".$this->session->userdata('id').";");
//$this->db->set('points' , 'points+1');
//$this->db->where('user_id', $this->session->userdata('id'));
//$this->db->update('challenges_scores');
}else{
// unSet
$this->session->unset_userdata('is_stopped');
}
return TRUE;
}else{
return FALSE;
}
}
now my problem is when the user post the input (the answer), the query is refreshed, then the answer is changed then the form input answer is wrong.
is there any way to save data to use it after the post ?
The logic is the same as an update form:
Model:
function get() {
return $this->db->get('sometable')->result();
}
Controller:
function index() {
$data['result'] = $this->sommodel->get();
$this->load->view('someview', $data);
}
Here we get the post value if there is any (in case of bad form validation submit) and if not we have the value from the db
<input name="somefield" value="<?php isset($_POST['somefield']) { echo $_POST['somefield'] } else { echo $result->somefield; } ?>">
If it's just one thing just store it in a session variable and do the same logic by instead of $result->somefield you put $this->session->somefield. I wouldn't recommend this approach if it's alot of data.

Redirecting not working in codeigniter

So here's what I want to do. I want to check if the userid in segment(3) exist or else it will redirect somewhere instead of still loading the view with an error.
Here's the example url
http://localhost/ems/edit_user/edit_user_main/1001
Now if I try to edit the userid in segment(3) and intentionally put an invalid userid, it still loads the view and i don't know why
Here's my function
public function edit_user_main(){
$id = $this->uri->segment(3);
$check = $this->get_data->check_if_exist($id);
if($check) {
$data['title'] = 'Edit User';
$data['id'] = $this->session->userdata('usertoedit');
$this->load->model('accounts/get_data');
$item = $this->get_data->get_user($id);
$data['user'] = $item[0];
$data['main_content'] = 'edit_user/edit_user_main';
$this->load->view('includes/template', $data);
} else {
redirect('admin/adminuser');
}
}
Here's the model
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query) {
return TRUE;
} else {
return FALSE;
}
}
There is no problem with the fetching of data.
The problem is even if the userid doesn't exist, the view is still loading but with an error coz there's no data for that userID. It's not redirecting,
I tried using print_r and it working fine, the value of the $check is 1 when there's a valid userID.
Hope someone can help me with this. Thank you
With your function it will always return true because the statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always execute,So you need to check query is returning any result row or not with the statement
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
Try this..
With the function it will always return true because the following statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always be execute, So need to check query is returning any result row or not
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
And load heper as:-
$this->load->helper('url');
before the redirection

REST API with CodeIgniter

I am creating a web-service backend for a mobile app I am developing. (I am an experience Obj-C developer, not a web-designer!) Essentially I would like to use Codeigniter and Phil Sturgeon's RESTful API Server https://github.com/philsturgeon/codeigniter-restserver however, I'm having some trouble getting it all setup and working.
I have MySQL database that is setup with data in it. And I need some help writing a CodeIgniter PHP model and controller that returns JSON data of what is inside that database. All of the tutorials and forum post's i have found deal with hardcoded data in the controler, not a MySQL database. I would ideally like to have the URL formatted like this http://api.mysite.com/v1/search?id=1&name=foo&city=bar , I could potentially have 50+ parameters to pass in the url.
Using Phil's code, I have come up with this as my controller:
public function index_get()
{
if (!$this->get('id'))
{
$this->response(NULL, 400);
}
$data = $this->grid_m->get_id($this->get('id'));
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
That only gets me one search term: id?=# .. I need to know how to get multiple search terms
Here is my Codeigniter model:
<?php
class Grid_m extends CI_Model
{
function get_all()
{
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}
This just returns EVERYTHING in my MySQL database regardless of what id or url term I pass it in the URL.
I'm a big noob when it comes to developing my own custom API so any suggestions on how to fix my controller and database model would be a huge help!
Thanks for the help!
-brian
This is old question but if somebody go here and still need help, try these code:
In your controller:
public function index_get()
{
$where = '';
if ($this->get('id')) // search by id when id passed by
{
$where .= 'id = '.$this->get('id');
}
if ($this->get('name')) // add search by name when name passed by
{
$where .= (empty($where)? '' : ' or ')."name like '%".$this->get('name')."%'";
}
if ($this->get('city')) // add search by city when city passed by
{
$where .= (empty($where)? '' : ' or ')."city like '%".$this->get('city')."%'";
}
// you can add as many as search terms
if ( ! empty($where))
{
$data = $this->grid_m->get_searched($where);
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
else
{
$this->response(NULL, 404);
}
}
In your model, create get_searched function:
class Grid_m extends CI_Model
{
function get_searched($where = NULL)
{
if ( ! is_null($where))
{
$this->db->where($where);
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
}
return FALSE;
}
}
User Codeigniter's Active record to build proper query, you can build any type of query using methods of active record, refer following example I have just added one condition in it you can add more conditions as per your need.
<?php
class Grid_m extends CI_Model
{
function get_all()
{
$this->db->select('col1, col2, col3')->where('id', 5);
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}
}
Please check you query
$query = $this->db->get_where('grid', array('id' => $id));

Codeigniter return username based on id

I created a helper for returning a user's username if the user's unique id is known.
if ( ! function_exists('get_username'))
{
function get_username($user_id)
{
$ci=& get_instance();
$ci->load->database();
if (empty($user_id))
{
return FALSE;
}
$ci->db->select('username');
$ci->db->where('id', $user_id);
$ci->db->where('activated', 1);
$ci->db->where('banned', 0);
$ci->db->limit(1);
$query = $ci->db->get('users');
if ($query->num_rows() > 0) //if user exists
{
$row = $query->row();
return $row->username;
}
else
{
return FALSE;
}
}
}
This works in my view if for instance I try:
echo get_username($this->uri->segment(3)); //uri segment 3 is a user id.
However want to send the username to my view via controller. I tried the following in my controller:
function write_message($user_id = '') //function parameter is 3rd uri segment
{
$data['username'] = get_username($user_id);
$this->load->view('my_view', $data);
}
Then in my view I have
echo $username which echoes array instead of the username. What am I doing wrong here?
Your criteria should be clear, and the usrname should be unique i think, so...
if ($query->num_rows() == 1) //if user exists, and unique
{
$res = $query->result_array();
return $res[0]['username'];
}
else
{
return FALSE;
}
Upon using <pre>print_r($username)</pre> in my view (as suggested by Alfonso) it was easy to spot the issue, being an identical variable name in my view which was another array. Correct answer goes to anyone that gives a good suggestion/input for my helper or Alfonso if he submits his post as answer.

How to get user name from the table in codeigniter

I have 2 tables one keeps the log and the other one keeps the user name.
Table one(logs) has
ID|USERID|DATETIME|MESSAGE
Table two(users) has
ID|USERNAME|PASSWORD
In codeigniter model I have
function getRlog(){
$this->db->limit(100);
$this->db->order_by("id","desc");
$this->db->where('type', "reservation");
$q = $this->db->get('logs');
if($q->num_rows() > 0) {
foreach($q->result() as $row){
$data[] = $row;
}
return $data;
}
}
In the controller I have...
function log(){
if (!$this->ion_auth->is_admin())
{
$this->session->set_flashdata('message', 'You must be an admin to view this page');
redirect('auth/login');
} else {
$data ['user'] = $this->ion_auth->get_user();
$this->load->model('Logs_model');
$data['logs'] = $this->Logs_model->getRlog();
$this->load->view('database/log', $data);
}
}
I want to get the username from the users table based on the id from the logs table. Should I create a foreign key? and If I do how do I get the username?
you might do it this way in your model
function getRlog(){
$this->db->limit(100);
$this->db->order_by("id","desc");
$this->db->where('type', "reservation");
$q = $this->db->get('logs');
if($q->num_rows() > 0) {
$data = array(); //create new data array to be returned
foreach($q->result() as $row){
$row->user = $this->ion_auth->get_user($row->userid); //create new user property that contains user object
$data[] = $row; //append to new data array with appended user property
}
return $data;
}
else {
return false; //if no results make sure you return something, either false or empty array depending on your needs.
}
}
This way you can access the entire user object from your log results returned from the model like so, assuming your controller stays the same.
View
foreach($logs as $log) {
echo $log->user->username;
}
or even...
foreach($logs as $log) {
echo $log->user->email; //etc...
}

Categories