migs
migs

Reputation: 113

Can't display values for a user profile in CodeIgniter?

I am making a simple twitter clone for practice with CodeIgniter and am having difficulty echoing the first_name and last_name and date_joined value from my users table in my user.php view. I just want to show the values for the user that is currently logged in.

I would want the values to echo below the session username in my view. My controller, view, and models are below. Right now I get the following error:

Message: Cannot use object of type stdClass as array

This is when I just try to echo $user['first_name'], $user['last_name], etc. I had it working before simply echoing out like this but now I can't. If I do a var_dump of $user I just get the following:

/app/www/application/views/user.php:5: class stdClass#22 (1) { public $user_id => string(1) "1" }

Controller: User.php

class User extends CI_Controller
{
 function index()
 {
  $this->load->model('login_model');
  $data['user'] = $this->login_model->get_user();
  $data['tweets'] = $this->tweet_model->usertweets();
  $this->load->view('templates/header');
  $this->load->view('user', $data);
  $this->load->view('templates/footer');
 }
}

Model: Login_model.php

class Login_model extends CI_Model
{
 function can_login($username, $password)
{
 $this->db->where('username', $username);
 $this->db->where('password', $password);
 $query = $this->db->get('users');

 //SELECT * FROM users WHERE username = '$username' AND password = '$password'

 if($query->num_rows() > 0)
 {
  return true;
 }
 else {
  return false;
 }
}

 function get_user()
 {
  $query = $this->db->get('users');

  $username = $_SESSION['username'];
  $this->db->select('user_id', 'first_name', 'last_name', 'date_joined');
  $this->db->from('users');
  $this->db->where('username', $username);
  $query = $this->db->get();
  return $query->row();
 }
}

Model: Tweet_model.php

class Tweet_model extends CI_Model
{
public function __construct()
{
    $this->load->database();
}

public function get_tweets($tweet_id = false)
{
    if ($tweet_id === false) {
        $this->db->join('users', 'tweets.user_id = users.user_id');
        $query = $this->db->get('tweets');
        return $query->result_array();
    }

    $query = $this->db->get_where('tweets', array('tweet_id' => $tweet_id));
    return $query->row_array();
}

public function set_tweet()
{
    $tweet = url_title($this->input->post('tweet'), 'dash', true);

    $query = $this->db->get('users');

    $username = $_SESSION['username'];
    $this->db->select('user_id');
    $this->db->from('users');
    $this->db->where('username', $username);

    if ($this->db->affected_rows())
    {
        $user = $query->row();
        var_dump($user_id);
    }

    $data = array(
      'tweet' => $this->input->post('tweet'),
      'user_id' => $user->user_id
    );

    return $this->db->insert('tweets', $data);
}

function Usertweets() {
  $this->db->flush_cache();

  $username = $_SESSION['username'];
  $this->db->select('user_id');
  $this->db->from('users');
  $this->db->where('username', $username);

  $query = $this->db->get();
  $user = $query->row();

  $this->db->flush_cache();

  $this->db->select('*');
  $this->db->from('tweets');
  $this->db->where('user_id', $user->user_id);

  return $this->db->get()->result();

}
}

View: user.php

<div class="container">
 <div class="row">
  <div class="col-md-4">
   <h4><?php echo $_SESSION['username']; ?></h4>
  </div>
  <div class="col-md-8">
   <?php foreach ($tweets as $tweet): ?>
    <div class="user-tweet">
     <h4><?php echo $_SESSION['username']; ?></h4>
     <h6><?php echo $tweet->tweet_date; ?></h6>
     <p><?php echo $tweet->tweet; ?></p>
    </div>
   <?php endforeach; ?>
  </div>
 </div>
</div>

Upvotes: 0

Views: 651

Answers (2)

Alex
Alex

Reputation: 9265

Generally any CI db function call that doesn't contain array somwhere in the name returns an object such as row() or result() with their array counterparts being row_array() and result_array().

Arrays are accessed like $arr['somevalue'] in the view and objects are accessed like $obj->somevalue. I can't track down your error because everything looks ok, but I suspect you might be getting no rows and thus foreach fails. Before foreach it is always a good idea to check if you have anything to print!

<div class="col-md-8">
    <?php if (count($tweets) > 0): ?>
    <?php foreach ($tweets as $tweet): ?>
        <div class="user-tweet">
            <h4><?php echo $_SESSION['username']; ?></h4>
            <h6><?php echo $tweet->tweet_date; ?></h6>
            <p><?php echo $tweet->tweet; ?></p>
        </div>
    <?php endforeach; ?>
    <?php else: ?>
    No tweets!
    <?php endif; ?>
</div> 

Code Review

First off, in your get_users function remove the first $query = $this->db->get('users'); as it is unnecessary.

Refactor can_login to:

function can_login($username, $password) {
    $this->db->where('username', $username);
    $this->db->where('password', $password); 
    return $this->db->count_all_results('users') > 0; // or == 1
}

Refactor set_tweet following the DRY principle:

public function set_tweet() {
    $this->load->model('login_model');
    $tweet = url_title($this->input->post('tweet'), 'dash', true);
    $data = array(
        'tweet' => $this->input->post('tweet'),
        'user_id' => $this->login_model->get_user()->user_id
    );
    return $this->db->insert('tweets', $data);
}

Should note as a general good practice that you should probably store the user_id in a session at login if you are using this that much; it will reduce database strain. Further, I assume that you don't let any of these actions happen if the user isn't logged in as$user_id or any of the user related row fields won't be accessible and will throw a notice if you try and access them. Redirect the user to login somewhere if (in your case) $_SESSION['username'] isn't set.

Following the previous refactor you can refactor Usertweets to:

function Usertweets() {
    $this->load->model('login_model');
    //$this->db->select('*'); * is done for you by default
    $this->db->where('user_id', $this->login_model->get_user()->user_id);
    return $this->db->get('tweets')->result(); // object returned
}

You might want to consider returning an object to keep everything the same in get_tweets as well.

Upvotes: 0

ShoeLace1291
ShoeLace1291

Reputation: 4698

You are getting this error because $query->row() returns an object which means you get the values with $user->user_id, not $user['user_id']. If you want to use $user['user_id'], change

$user = $query->row();

to

$user = $query->row_array();

Upvotes: 0

Related Questions