2016-02-12 31 views
0

我對mysqli prepared語句有點新,我想用fetch_array返回結果並且還返回num_rows作爲數組值。返回array和num的行mysqli編寫

我有這樣的事情

function getCategories($dbh, $catId) 
{ 
    $data = array(); 
    $s = "SELECT id, title FROM categories WHERE parent_id = ?"; 
    if ($stmt = mysqli_prepare($dbh, $s)) { 
     mysqli_stmt_bind_param($stmt, "i", $catId); 
     mysqli_stmt_execute($stmt); 
     if (mysqli_stmt_errno($stmt)) { 
      exit(mysqli_stmt_error($stmt)); 
     } 
     mysqli_stmt_store_result($stmt); 
     $count = mysqli_stmt_num_rows($stmt)) { 
     if ($count) { 
      $data['count'] = $count; 
      $result = mysqli_stmt_get_result($stmt); 
      while ($r = mysqli_fetch_assoc($result)) { 
       $data[] = $r; 
      } 
     } 

     return $data; 
    } else { 
     exit(mysqli_error($dbh)); 
    } 
} 

看來,我不能用mysqli_stmt_store_result和mysqli_stmt_get_result()。

的store_result功能似乎給了一個布爾值,然後我得到這個錯誤:「mysqli_fetch_assoc()預計參數1被mysqli_result,鑑於布爾」

希望這是有道理的。任何幫助將非常感激。

更新時間:

function getCategories($dbh, $catId) 
{ 
    $data = array(); 
    $s = "SELECT id, title FROM categories WHERE parent_id = ?"; 
    if ($stmt = mysqli_prepare($dbh, $s)) { 
     mysqli_stmt_bind_param($stmt, "i", $catId); 
     mysqli_stmt_execute($stmt); 
     if (mysqli_stmt_errno($stmt)) { 
      exit(mysqli_stmt_error($stmt)); 
     } 

     $result = mysqli_stmt_get_result($stmt); 
     $data['count'] = $result->num_rows; 
     while ($r = mysqli_fetch_assoc($result)) { 
      $data[] = $r; 
     } 

     return $data; 
    } else { 
     exit(mysqli_error($dbh)); 
    } 
} 

回答

1

按照PHP文檔,mysqli_stmt_get_result回報FALSE上的錯誤:

Returns a resultset for successful SELECT queries, or FALSE for other DML queries or on failure. The mysqli_errno() function can be used to distinguish between the two types of failure.

你再傳遞到這mysqli_fetch_assoc它抱怨,因爲你給它一個布爾而不是它期望的結果集。

在這一點做更多的錯誤檢查,你會沒事的。您的SQL查詢可能有問題。請致電mysqli_errorno以確定是否有錯誤,如上述文檔所述。

編輯:

使用mysqli_error函數來獲得MySQL錯誤的描述。最好在檢查失敗的任何地方使用它,因爲出現錯誤信息會使調試比簡單的失敗更容易。

+0

沒有從mysqli_stmt_get_result得到任何錯誤.....嗯在這裏撓我的頭 – Programit

+0

@Programit你的意思是你得到一個錯誤信息?按定義返回'FALSE'的'mysqli_stmt_get_result'意味着您收到錯誤。 – Skrat

+0

啊我已經想通了。如果你var_dump,mysqli_stmt_get_result實際上會返回num_rows – Programit