2014-10-07 114 views
0

我想創建的基本上是類似Facebook的東西。如果用戶發佈了他/她的用戶名,則鏈接將如下所示:www.mysite.com/user/{username},如果不是,則鏈接將如下所示:www.mysite.com/user/{userid}。使用下面的代碼,我得到了我試圖從數據庫中檢索的所有字段的未定義索引。它只與user_id一起使用,但不與用戶名一起使用。任何幫助將非常感激。CodeIgniter通過用戶名獲得用戶信息,如果用戶名存在,如果沒有得到用戶ID

鏈接到簡檔(查看):

<a href="<?=base_url()?>user/<?=isset($event['username']) ? $event['username'] : $event['creatoruserid']?>"> 
    <img src="<?=base_url()?>public/images/uploads/profiles/<?=$event['profilepic']?>" class="event-profile-pic"> 
</a> 

路由到配置文件:

$route['user/(:any)'] = "user/profile/$1"; 

用戶控制器與用戶的方法:

<?php 

class User Extends CI_Controller 
{ 

    public function __construct() 
    { 

     parent::__construct(); 
     $this->load->model('event_model'); 
     $this->load->model('user_model'); 
    } 

    public function profile($user_id) 
    { 
     // All the data we need in profile page 

     $data['user'] = $this->user_model->getUserInfo($user_id); 
     $data['events'] = $this->event_model->getEventsById($user_id); 
     $data['total_events_created'] = $this->user_model->TotalEventsCreated($user_id); 
     $data['total_comments'] = $this->user_model->TotalComments($user_id); 
     $data['total_attending_events'] = $this->user_model->TotalAttendingEvents($user_id); 

     $this->load->view('/app/header'); 
     $this->load->view('/app/profile', $data); 
     $this->load->view('/app/footer'); 

    } 
} 

型號從數據庫中檢索用戶信息:

<?php 

class User_model extends CI_Model 
{ 

    public function getUserInfo($user_id) 
    { 

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

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

     return $query->first_row('array'); 
    } 
} 

回答

0

你可以在你的SQL層中處理這個。建議是通過用戶名或用戶ID來查找用戶記錄。因此,在SQL(笨活動記錄),你可以這句話爲:

$this->db->select('*') 
     ->from('users') 
     ->where(['user_id' => $user_id]) 
     ->or_where(['user_name'] => $user_id]) 
     ->limit(1); 

在這種情況下,我們假設$user_id可以是一個字符串(USER_NAME)或一個整數(USER_ID)。我們還假設您沒有數字的user_names,偶然可能會匹配user_id。要防止返回多行,可以將limit添加到查詢中。

一旦你有一個用戶記錄,那麼你將需要在其他查詢中傳遞找到的用戶記錄的user_id,而不是傳遞給該函數的user_id。

+0

or_where做的伎倆,歡呼兄弟! :) – Cooper 2014-10-07 15:52:41

0

請確保您的「用戶名」是在DB匹配列名,並可以添加回聲語句,如回聲「A」;回聲'B';確定究竟哪裏是未定義的索引錯誤是?

相關問題