2015-11-28 37 views
0

所以我有一些困難,理解爲什麼,如果我使用返回在我的函數結束它不會返回所有的值,但只有一個。 但是,如果我使用回聲,所有值得到顯示。 新功能和試圖理解和利用他們更多。任何解釋都非常感謝。返回不檢索while循環的所有數據

function find_all_users($Teacher_role) { 
global $mysqli; 
if ($Teacher_role == "teacher") { 
    $set_update_role = "teacher"; 
} 
$set_visable = 1; 
if (!($stmt = $mysqli->prepare("SELECT user_id, user_email, first_name, last_name, role FROM users WHERE role = ? AND visible = ? ORDER BY user_id ASC"))) { 
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; 
} 
/* 2 Bind params */ 
if (!$stmt->bind_param("si", $Teacher_role, $set_visable)) { 
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; 
} 
/* 1 Execute statements */ 
if (!$stmt->execute()) { 
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; 
} 
$result = $stmt->get_result(); 
// output data of each row 

while ($row = mysqli_fetch_assoc($result)) { 
    $user_id = $row["user_id"]; 
    $user_email = $row["user_email"]; 
    $user_Fname = $row["first_name"]; 
    $user_Lname = $row["last_name"]; 
    $user_role = $row["role"]; 

    $output = "<tr>"; 
    $output .= "<td>" . $user_id . "</td>"; 
    $output .= "<td>" . $user_email . "</td>"; 
    $output .= "<td>" . $user_Fname . "</td>"; 
    $output .= "<td>" . $user_Lname . "</td>"; 
    $output .= "<td>" . $user_role . "</td>"; 
    $output .= "<td> <a href='update_" . $set_update_role . ".php?id=" . $user_id . "'>Edit</a>" . "</td>"; 
    $output .= "</tr>"; 
    return $output; 
} 

mysqli_close($mysqli);} 
+0

看看'return'手冊,它會立即停止函數,並且所有的代碼都不會被執行。 – Rizier123

+0

那麼在這種情況下,我應該使用「回聲」?或者有沒有辦法用「返回」來做到這一點? – Rudi

+1

您可以將數據存儲在數組中,然後將其返回。 – Rizier123

回答

0

不要在while循環中返回$ output。第一次運行循環時,您的$輸出值立即返回。讓while循環爲所有值構建$ output,並且僅在完成所有操作後返回$ output。

$output = ''; 
    while ($row = mysqli_fetch_assoc($result)) { 
     $user_id = $row["user_id"]; 
     $user_email = $row["user_email"]; 
     $user_Fname = $row["first_name"]; 
     $user_Lname = $row["last_name"]; 
     $user_role = $row["role"]; 

     $output .= "<tr>"; 
     $output .= "<td>" . $user_id . "</td>"; 
     $output .= "<td>" . $user_email . "</td>"; 
     $output .= "<td>" . $user_Fname . "</td>"; 
     $output .= "<td>" . $user_Lname . "</td>"; 
     $output .= "<td>" . $user_role . "</td>"; 
     $output .= "<td> <a href='update_" . $set_update_role . ".php?id=" . $user_id . "'>Edit</a>" . "</td>"; 
     $output .= "</tr>"; 

    } 

    mysqli_close($mysqli); 

    return $output; 
+0

我仍然只返回一行。但現在它是數據庫中的最後一個,而不是第一個。 – Rudi