【问题标题】:return does not retrieve all data from while loopreturn 不会从 while 循环中检索所有数据
【发布时间】:2016-03-02 13:14:19
【问题描述】:

所以我很难理解为什么,如果我在函数末尾使用 return 它不会返回所有值,而只会返回一个。 但是如果我使用 echo,所有值都会显示出来。 新功能并尝试更多地理解和使用它们。任何解释都非常感谢。

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);}

【问题讨论】:

  • 看一下:return的手册,它会立即停止函数,之后的所有代码都不会执行。
  • 那么在这种情况下我应该使用 "Echo" 吗?或者有没有办法用“return”来做到这一点?
  • 可以将数据存储在数组中,然后返回。

标签: php function mysqli return echo


【解决方案1】:

不要在 while 循环中返回 $output。您的 $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;

【讨论】:

  • 我仍然只返回一行。但现在它是数据库中的最后一个,而不是第一个。
猜你喜欢
  • 1970-01-01
  • 2016-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2015-05-11
  • 2013-02-08
  • 2022-11-03
相关资源
最近更新 更多