2016-12-29 151 views
0

我有一個PHP類我在哪裏initilizing在構造從數據庫retieved數組:如何通過PHP中獲取查詢循環使用的MySQL

class TableClass{ 
    public function __construct($con, $id){ 
     $this->con = $con;    
     $query = mysqli_query($this->con, "SELECT * FROM table1 WHERE id='$id'"); 
     $this->table_result= mysqli_fetch_array($query); 
    } 
} 

我有,我想用數組不同的功能而不必再次獲取。我只需要循環查看結果並進行一些計算。 我試過的語法如下:

public function getNumberOfComments(){ 
    for ($i = 0; $i < count($this->table_result); $i++) { 
      $comment= $this->table_result[$i]['comment'];      
    } 
} 

我得到一個錯誤:Illegal string offset "comment"

什麼是正確的語法?

+2

您只從結果集中提取一行,那麼爲什麼使用'for'循環呢?簡單的'$ comment = $ this-> table_result ['comment'];'會做得很好。 –

+0

首先嚐試'print_r'結果'$ this-> table_result'來查看究竟究竟是什麼被提取 –

回答

3

您是從結果集中讀取一行:

$this->table_result= mysqli_fetch_array($query); 

假設id是主鍵,你會在你的結果集0或1行,所以如果行被發現,你可以直接訪問字段,而使用循環:

$comment= $this->table_result['comment']; 
+1

我們都發布了幾乎同一時間。 ;-) –

+0

我很好奇;因爲它們是用'$ this-> con = $ con;'構造的,並將2個參數傳遞給構造函數,所以'$ id'是否也包含一個屬性? –

+0

@ Fred-ii-可能,取決於班級的其他人。從我所看到的甚至'$ this-> con'都是未使用/不需要的,但也許在其他方法中...... – jeroen

0

非法串偏移「註釋」是告訴你的$this->table_result[$i]值不是一個數組,因此不包含元素命名爲comment

問題可能是由構造函數中的代碼無法正常工作引起的;你在那裏沒有任何錯誤檢查,所以如果失敗了,它不會告訴你。

在構造函數中添加一些錯誤檢查,找出它失敗的原因並進行修復。