Executing mysqli prepared statment within while loop that's within another while loop

谁都会走 提交于 2021-02-04 21:47:45

问题


I am trying to achieve the following:

User 1:
     - Alert 1 Email
     - Alert 2 Email
User 2:
     - Alert 1 Email
     - Alert 2 Email

I'm trying to accomplish this with a while loop inside another while loop that is running a mysqli prepared statement, but I cannot get it to work.

Code:

$stmtAdd = $conn->prepare("INSERT INTO Data (row1, row2, row3, row4) VALUES ('".$row1."', '".$row2."', '".$row3."', '".$row4."')");
$stmtAdd->execute();
$stmtAdd->close();

$stmtUsers = $conn->prepare("SELECT username, setting1 FROM Users");
$stmtUsers->store_result();
if ($stmtUsers->execute() === FALSE) {
    die("Could not execute prepared statement");
} else {
    $stmtUsers->bind_result($user, $setting1);
    while ($stmtUsers->fetch()) {
        /* Check if each user has setting 1 disabled */
        if ($setting1 == '0'){
            /* Check if any alerts exist for each user */
            $stmtUsersAlerts = $conn->prepare("SELECT name, filter, email FROM Alerts WHERE user='".$user."' AND type='1'");
            $stmtUsersAlerts->store_result();
            $stmtUsersAlerts->bind_result($name, $filter, $email);
            while ($stmtUsersAlerts->fetch()) {
                /* Send email */
            }
            $stmtUsersAlerts->close();
        }
    }
    $stmtUsers->close();
}

回答1:


stmt->store_result() can not run before stmt->execute().

$stmtUsers = $conn->prepare("SELECT username, setting1 FROM Users");
if ($stmtUsers->execute() === FALSE) {
    die("Could not execute prepared statement");
} else {
    $stmtUsers->store_result();                // After execute()
    $stmtUsers->bind_result($user, $setting1);
    while ($stmtUsers->fetch()) {
        /* Check if each user has setting 1 disabled */
        if ($setting1 == '0'){
            /* Check if any alerts exist for each user */
            $stmtUsersAlerts = $conn->prepare("SELECT name, filter, email FROM Alerts WHERE user='".$user."' AND type='1'");
            $stmtUsersAlerts->execute();        // This line was missing
            $stmtUsersAlerts->store_result();
            $stmtUsersAlerts->bind_result($name, $filter, $email);
            while ($stmtUsersAlerts->fetch()) {
                /* Send email */
            }
            $stmtUsersAlerts->close();
        }
    }
    $stmtUsers->close();
}


来源:https://stackoverflow.com/questions/32552042/executing-mysqli-prepared-statment-within-while-loop-thats-within-another-while

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!