2016-12-06 33 views
0

我有數據,其中的數據包含我的ID作出關鍵字,我試圖分開ID並採取了4位數的樣本ID「PRNE4」,但我試圖使腳本顯示錯誤?哪裏不對?條件'WHERE'的子串錯誤CodeIgniter

我的鏈路

http://localhost/project/profile/get/PRNE

錯誤

消息:的foreach()

我Smple ID

供給參數無效
PRNE1 
PRNE2 

控制器

public function Index($) { 
    $id = $this->uri->segment(3); 
    $data = array (
        'profile' => $this->M_model->get_profile($id)); 
    $this->load->view('layout/wrapper', $data); 
} 

模型

function get_profile($id) { 
    $query = $this->db->select('*') 
         ->from('tb_sample') 
         ->where("(SUBSTRING(id_sample, 0, 4) = '$id')") 
         ->get(); 

    if ($query->num_rows() > 0) { 
     foreach ($query->result() as $data) { 
      $hasil[] = $data; 
     } 
     return $hasil; 
    } 
} 

查看

<?php 
    $no = 1; 
    foreach ($profile as $row) { 
     echo '<tr>'; 
     echo '<td>'.$no.'</td>'; 
     echo '<td>'.$row->name.'</td>'; 
     echo '<td>'.$row->profile.'</td>'; 
     echo '</tr>'; 
    $no++; 
} ?> 

回答

1

SUBSTRING醫生說

對於所有形式的SUBSTRING(),則第一個字符的 從中子是要被提取被算作 1.

->where("(SUBSTRING(id_sample, 1, 4) = '$id')") 

所以第一個位置是1,而不是串的位置0.

同樣在你的模型中,如果查詢的結果是空的,get_profile函數就沒有返回值。您可以可以返回$query在其他答案建議,並在視圖中使用的對象,如果你想保留您的格式在函數的最後返回一個空數組:

function get_profile($id) { 
    $query = $this->db->select('*') 
         ->from('tb_sample') 
         ->where("(SUBSTRING(id_sample, 1, 4) = '$id')") 
         ->get(); 

    if ($query->num_rows() > 0) { 
     foreach ($query->result() as $data) { 
      $hasil[] = $data; 
     } 
     return $hasil; 
    } 
    return array(); 
} 
+0

謝謝@ phobia82,是ID數據有5個字符,但將用作關鍵字,如uri->段,所以我採取了由字符串分隔的數據庫的4個字符...ID ='PRNE1',我期望它='PRNE' –

+0

哦,明白了,在SUBSTRING中,第一個位置是1,而不是0,現在更新我的答案 – phobia82

+0

haha​​haha求助....這只是她的問題,爲什麼不是從'0'開始,因爲這一次我使用'0'作爲子串中的第一個值,是否使用不同的子串mysql和php? –

0

試試這個。

在控制器

public function index() { 
    $id = $this->uri->segment(3); 
    $data['profile'] = $this->M_model->get_profile($id); 
    $this->load->view('layout/wrapper', $data); 
} 

在型號

function get_profile($id) { 
    $this->db->select('*') 
    $this->db->from('tb_sample') 
    $this->db->where("(SUBSTRING(id_sample, 5) = '$id')") // if PRNE4 => 4 (cut the string start for pos of 5) 

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

在查看

<?php 
    $no = 1; 
    foreach ($profile->result() as $row) { 
     echo '<tr>'; 
     echo '<td>'.$no.'</td>'; 
     echo '<td>'.$row->name.'</td>'; 
     echo '<td>'.$row->profile.'</td>'; 
     echo '</tr>'; 
     $no++; 
    } 
?> 
+0

感謝@Soe捷Kaung,後我嘗試腳本時遇到錯誤,在索引()上添加'$',在'$'不是錯誤但未找到數據後刪除它。 –

+0

嘿。 @irwan dwiyanto,我編輯了代碼。再試一次。如果還沒有找到數據。只是評論'where'行,看看是否有數據。 –