简体   繁体   中英

IF Statement not working in while loop PHP?

Hi I am trying to stop one part of a while loop from only running ONCE.

I have searched and an IF statement seems to be the only way

The only thing is,when i put IF statement in - it doesn't seem to DO the INSERT statement at all, so nothing is being inserted, it's as if it's stopping before insert statement. As you can see $inserted is declared outside the loop and then changed to true inside so it stops, but it doesn't seem to be doing that.

Without it, it will loop each time the page is refreshed and insert into the database each refresh of the page, although i only need the INSERT statement to run once. I need it in the loop as that's where the information for the insert is.

Can anyone help here?

Try this, and then let us know what the errors are. If it's not inserting, it could be an error within PDO that you need to know of.

    if (!$inserted) {
        $inserted = true;
        try {
            $stmt = $conn->prepare("INSERT into UserRecipes (UserID, RecipeID, Displayed) VALUES (:UserID, :RecipeID, :Displayed) ");
            $stmt->execute(array(
                ':UserID' => $UserID,
                ':MealID' => $MealID,
                ':Displayed' => $Displayed
            ));
        } catch (PDOException $p) {
            print $p;
            exit;
        }
    }

I have tried to fix your quotes were too bad

    <?php

$inserted=false;

while($dbRow=$dbQuery->fetch(PDO::FETCH_ASSOC) and ($cnt < $max))  
    {
     echo ''.$dbRow["Name"].'<br><img src="\"'.$dbRow["Picture"].' width="150" height="150" /><br><br>'.$dbRow["Instructions"].'

<form method="POST"><input type="hidden" name="MealID" value= "'.$dbRow['MealID'].'">
<input type="submit" name="submit" value="Complete" ></form>';

$cnt++;


$MealID=$dbRow["MealID"];
$Displayed = false;
if (!$inserted) {
$inserted=true;
$stmt=$conn->prepare("INSERT into UserRecipes (UserID, RecipeID, Displayed) VALUES (:UserID, :RecipeID, :Displayed) "); 
$stmt->execute(array(
       ':UserID' => $UserID,
       ':MealID' => $MealID,
       ':Displayed' => $Displayed
        )); 
   }
    }


?>

let me hope i have not missed any thing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM