Click here to Skip to main content
16,005,389 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
For the code below, the Insert statement I only need to happen ONCE. When the while loop is performed and the items are displayed for user.

is there anyway to do this?

I need duplicate entries in the database so I cant do that. see code below


What I have tried:

$insertedMeal = false;
while($dbRow=$dbQuery->fetch(PDO::FETCH_ASSOC) and ($cnt < $max)) 
{
  echo "//displays information from table"
  $cnt++;
  $MealID=$dbRow["MealID"]
if (!$insertedMeal) {
    $insertedMeal = true;

$stmt=$conn->prepare("INSERT into Meals (UserID, MealID) VALUES (:UserID, :MealID) "); 
$stmt->execute(array(
':UserID' => $UserID,
':MealID' => $MealID
));
 } //end
Posted
Updated 2-Apr-18 4:43am
v3

Not sure if I understand the question correctly, but with your current code the insert statement will be executed as many times as the loop iterates. So if you want to run the statement only once, move it outside the loop.

In the description you say that you need duplicate values in the database. That leaves some questions concerning the database structure. It could well be that the problem should actually be resolved by changing the database schema. But without further info this is merely guessing.
 
Share this answer
 
Comments
Member 13637584 2-Apr-18 5:58am    
When i move it outside the loop, it doesn't insert into the database correctly?
Wendelius 2-Apr-18 6:09am    
What do you mean by that? Is the insert using wrong values? If that is the case then you need to pick the values you want to use into some variables inside the loop and the use those variables outside the loop.
Member 13637584 2-Apr-18 6:16am    
I did try that as i kept $MealID=$dbRow["MealID"] inside the loop then referred to it outside the loop but still doesnt work right?
Wendelius 2-Apr-18 6:27am    
If you assign $MealID inside the loop without investigating anything then the $MealID will contain the last MealId when you exit the loop. Is this the problem?
Member 13637584 2-Apr-18 7:11am    
Yes thats exactly it?
This code is just wrong and can't execute because of 2 missing ')'
PHP
$stmt->execute(array(
':UserID' => $UserID,
':MealID' => $MealID
 
Share this answer
 
Comments
Member 13637584 2-Apr-18 6:09am    
Sorry, i do have that in the code. I have updated the above.
Patrice T 2-Apr-18 6:15am    
indeed it is better that way.
Member 13637584 4-Apr-18 8:07am    
@ppolymorphe do you have any solution to this issue??
Patrice T 4-Apr-18 8:22am    
Your code fragment is not complete and we can only guess what is going on.
My best option is to use a debugger to see what is going on in this code and with variables.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900