I got an error

I am going through the book Build Your Database Driven Web Site. I am on chapter 5 and I am trying to get the jokes.html.php page to load and work. I am getting this error when I try to install a joke to the data base. Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\chapter5\jokes\jokes.html.php on line 12

Here is the code I am working with I just do not see a problem on line 12.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>List of Jokes</title>
		<meta http-equiv="content-type"
				content="text/html; charset=utf-8"/>
	</head>
	<body>
		<p><a href="?addjoke">Add your own joke</a></p>
		<p>Here are all the jokes in the database:</p>
		<?php foreach ($jokes as $joke): ?>
			<form action="?deletejoke" method="post">
				<blockquote>
					<p>
						<?php echo htmlspecialchars($joke['text'], ENT_QUOTES,
								'UTF-8'); ?>
						<input type="hidden" name="id" value="<?php
								echo $joke['id']; ?>"/>
						<input type="submit" value="Delete"/>
						(by <a href="mailto:<?php
								echo htmlspecialchars($joke['email'], ENT_QUOTES,
										'UTF-8'); ?>"><?php
								echo htmlspecialchars($joke['name'], ENT_QUOTES,
										'UTF-8'); ?></a>)
					</p>
				</blockquote>
			</form>
		<?php endforeach; ?>
	</body>
</html>

Thank you in advance for all help Codin.:rofl:

$jokes has not been defined. You can’t iterate over something that does not exist. Though, if it has been defined (just not showing the code) then that error means that $jokes is not an array, in short.

$jokes is supposed to be an array, either it is empty or it has not been set. I am not familiar with the book you mention.
add this line right at the beginning of this file to see which it is, empty or not set.


<?php var_dump($jokes); ?>

You had better then check through the code carefully, because this file clearly does not even connect to the database. Find that code and check it, move that line I gave you to AFTER the connection to the database, and the subsequent call to fetch rows.

In the line of the file (can’t remember off hand which file) where the jokes are fetched from the database, add this line above the line where you fetch the result set (the jokes) from the database:

$jokes=array();

That will initiate the $jokes variable as an empty array, then when your using $jokes with the foreach it will always see an array, even if there are no jokes returned.