Problem with foreach loop

Hello there,

PHP noob here :lol:

I just bought ebook “Build your own database driven website using PHP and MySQL” and have a great reading! What a worth buy :wink:

I just finish chapter 4 with sample script of “Delete Joke”. I try myself this sample script and run it perfectly but when I delete all the jokes, I got an error :

Warning: Invalid argument supplied for foreach() in C:\Documents and Settings\Administrator\My Documents\xampp\htdocs\wikuu\deletejoke\jokes.html.php on line 19

Anyone got same problem and how to solve this little bug :smiley:

As many of us might not have read the book.
Can you post the code.

Thanks for your reply :slight_smile:

Here’s are the code :

<?php foreach ($jokes as $joke): ?>
<form action=“?deletejoke” method=“post”>
<p><?php echo htmlspecialchars($joke[‘text’], ENT_QUOTES, ‘UTF-8’); ?></p>
<input type=“hidden” name=“id” value=“<?php echo $joke[‘id’]; ?>”/>
<input type=“submit” value=“Delete” />
<?php endforeach; ?>

And this

if (isset($_GET[‘deletejoke’])) {
$id = mysqli_real_escape_string($link, $_POST[‘id’]);
$sql = “DELETE FROM joke WHERE id=‘$id’”;
if (!mysqli_query($link, $sql)) {
$error = 'Error adding submitted joke: ’ . mysqli_error($link);
include ‘error.html.php’;
header(‘Location: .’);

The source of the problem occurs earlier, when retrieving jokes from the database.

while ($row = mysqli_fetch_array($result))
  $jokes[] = $row['joketext'];

When there are no jokes, the $jokes variable fails to exist, causing the foreach to error.

Solution: create $jokes before the while loop.

$jokes = array();
while ($row = mysqli_fetch_array($result))
  $jokes[] = $row['joketext'];

Now the $jokes variable exists regardless of whether any jokes are in the database or not.

Thanks a lot, javascript guru of the year :smiley:

What? Hang on, this isn’t the right place! Ahhhhhh! :eek: