简体   繁体   English

IF语句不能在while循环PHP中工作?

[英]IF Statement not working in while loop PHP?

Hi I am trying to stop one part of a while loop from only running ONCE. 嗨,我试图阻止while循环的一部分仅运行一次。

I have searched and an IF statement seems to be the only way 我已经搜索过,IF语句似乎是唯一的方法

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. 唯一的是,当我放入IF语句时-似乎根本不执行INSERT语句,因此没有插入任何内容,就好像它在插入语句之前停止了一样。 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. 如您所见,$ inserted在循环外部声明,然后在内部更改为true,因此它停止了,但是似乎没有这样做。

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. 没有它,它将在每次刷新页面时循环并在每次刷新页面时将其插入数据库中,尽管我只需要INSERT语句即可运行一次。 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. 如果未插入,则可能是您需要知道的PDO中的错误。

    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 我希望我没有错过任何事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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