Foreach warning message

I have recently taken part in the Sitepoint PHP course and I am having a problem with a foreach loop.

Warning: Invalid argument supplied for foreach() in C:\wamp\www\…on line 53

The code I have works fine once content has been entered on the form but prior to that I get this warning.
So I think its a case of the table has not had data entered at that point therefore the select
query cant find anything so no array content
question how do I stop this warning appearing before the data is entered.

thanks Kevin

INDEX PHP

include $_SERVER[‘DOCUMENT_ROOT’] . ‘/includes/db.inc.php’;
$sql = “SELECT * FROM items WHERE order_id=‘$id’”;
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = ‘Error fetching item from database!’;
include ‘error.html.php’;
exit();
}
while ($row = mysqli_fetch_array($result))
{
$items = array(‘item_code’ => $row[‘item_code’],
‘item_description’ => $row[‘item_description’],
‘item_price’ => $row[‘item_price’],
‘card_message’ => $row[‘card_message’]);
}


DISPLAY PAGE
<?php foreach ($items as $item): ?>

&lt;li&gt;
 &lt;form action="" method="post"&gt;
  &lt;div&gt;
  &lt;p&gt;Item Code...&lt;?php htmlout($item['item_code']); ?&gt;&lt;/p&gt;
  &lt;p&gt;Description...&lt;?php htmlout($item['item_description']); ?&gt;&lt;/P&gt;
  &lt;p&gt;Price...&lt;?php htmlout($item['item_price']); ?&gt;&lt;/p&gt;
  &lt;p&gt;Card Message...&lt;?php htmlout($item['card_message']); ?&gt;&lt;/p&gt;
   
   &lt;input type="hidden" name="id" value="&lt;?php
     echo $item['id']; ?&gt;"/&gt;
   
  &lt;/div&gt;
 &lt;/form&gt;
&lt;/li&gt;

<?php endforeach; ?>

spikeZ & ScallioXTX

Many thanks that works a dream, I expect that I will be back as some point with more questions as I work through the project.

ScallioXTX

It was rather apt that you helped from The Netherlands the Fresh Flower capital of the world, since the site I am building it for our Florist shop to take orders. Most of our flowers come from Holland.

thanks Kevin

^ That works but can emit an E_NOTICE Variable not defined. I always make sure to initialize variables like this as an empty array:


$items=array();
while ($row = mysqli_fetch_array($result))
{
  $items[] = array('item_code' => $row['item_code'],
   'item_description' => $row['item_description'],
   'item_price' => $row['item_price'],
   'card_message' => $row['card_message']
  );
}

:slight_smile:

(or your could use (isset($items) && is_array($items)) )

You have it exactly right. If there is no array to iterate through it throws the error.

What you could do is check if the array exists firsts before trying the loop


if(is_array($items)) {
// if it is an array, run the foreach

and dont forget to close the } at the end :wink: