2016-12-28 34 views
0

我正在嘗試更改我的mysqli代碼以使用預準備語句。

由於某種原因,我不能得到通常的$row['']工作。我搜索了一段時間,但我不明白。我沒有準備好的語句代碼是這樣的:

if($result = mysqli_query($con,"SELECT * FROM users")) { 
     echo " 
      <thead> 
       <tr> 
       <th>1</th> 
       <th>2</th> 
       <th>3</th> 
       <th>4</th> 
       <th>5</th> 
       </tr> 
      </thead> 
      <tbody>"; 
     while($row = mysqli_fetch_array($result)) { 
      if($row['status'] == "1") { 
       echo '<tr class="active">'; 
      } elseif($row['status'] == "2") { 
       echo '<tr class="success">'; 
      } elseif($row['status'] == "0") { 
       echo '<tr class="danger">'; 
      } else { 
       echo '<tr class="warning">'; 
      } 
    etc... 

這是我迄今爲止預處理語句:

$grab_user = $db->prepare("SELECT * FROM users"); 
if($grab_user->execute()) { 
    echo " 
     <thead> 
      <tr> 
      <th>1</th> 
      <th>2</th> 
      <th>3</th> 
      <th>4</th> 
      <th>5</th> 
      </tr> 
     </thead> 
     <tbody>"; 

    while($grab_user->fetch()) { 
     $row = $grab_user->fetch_row(); 

     if($row['status'] == "1") { 
      echo '<tr class="active">'; 
     } elseif($row['status'] == "2") { 
      echo '<tr class="success">'; 
     } elseif($row['status'] == "0") { 
      echo '<tr class="danger">'; 
     } else { 
      echo '<tr class="warning">'; 
     } 

顯然,這似乎並沒有工作。我究竟做錯了什麼?

+0

我知道這並不真正回答你的問題,但對於這樣的靜態查詢,使用'mysqli_query()'沒有任何問題。用這樣的查詢使用準備好的語句並沒有太大的好處,因爲您沒有綁定任何參數。當你使用不同的輸入重複執行相同的語句時,準備好的語句主要用於幫助防止SQL注入並提高性能。 –

+0

我不是想說你不應該學習如何使用一般的準備語句。你絕對應該。這對於這個特殊情況不會有用。另外,當你確實需要綁定參數時,我認爲PDO比mysqli更容易處理。如果您尚未完成向預備陳述的轉換,則可以考慮嘗試使用PDO。 –

回答

1

fetch_row從結果集中提取一行數據並將其作爲枚舉數組返回,其中每列存儲在從0(零)開始的數組偏移中。

所以它應該是類似$row[0]。找出狀態的索引,然後使用適當的值。


如果您需要訪問列名稱,則需要使用fetch_assoc

這樣的:

while($row=$grab_user->fetch_assoc()) {  
    if($row['status'] == "1") { 
     echo '<tr class="active">'; 
    } elseif($row['status'] == "2") { 
     echo '<tr class="success">'; 
    } elseif($row['status'] == "0") { 
     echo '<tr class="danger">'; 
    } else { 
     echo '<tr class="warning">'; 
    } 
} 

fetch_row - 數字陣列

fetch_assoc - 關聯數組

+0

謝謝。並感謝@不要恐慌,因爲我查詢()更好地工作 – MMQVBN

1

如果你想要一個關聯數組,你應該使用fetch_assoc(),不fetch_row(),這返回一個數字數組。

此外,您不應該在循環中調用fetch()fetch_assoc()。他們每個人都會讀取下一行,所以fetch_assoc()只會得到結果的每一行。所以它應該是:

while ($row = $grab_user->fetch_assoc()) { 
    ... 
}