I´m reading Kevin Yank´s book “PHP and MySQL Novice to Ninja 5th edition”, and found an error there in the code, and would like someone to help me out with it, maybe is a silly typo…?
I´m trying to follow the author´s example of creating and accessing a database of jokes. I´m learning how to join two databases to show with php a list of all the jokes. I have two databases joke and author. I´ve got this:
try{
$sql = 'SELECT joke.id, joketext, jokedate, name, email
FROM joke INNER JOIN author
ON authorid = author.id';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error: ' . $e->getMessage();
include 'error.html.php';
exit();
}
foreach ($result as $row)
{
$jokes[] = array(
'id' => $row['id'],
'text' => $row['joketext'],
'date' => $row['jokedate'],
'name' => $row['name'],
'email' => $row['email']
);
}
include 'jokes.html.php';
Now, all was working ok, until I´ve replaced the simple code to select the database information from just one table, to the INNER JOIN code. This is the book´s code, wich I´ve followed.
In the jokes.html.php file, I´ve got this (wich I think is what´s giving me the error):
foreach($jokes as $joke):
<form action="?deletejoke" method="post">
<?php
echo 'id. ';
echo htmlspecialchars($joke['id'], ENT_QUOTES, 'UTF-8');
echo htmlspecialchars($joke['date'], ENT_QUOTES, 'UTF-8');
echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8');
echo htmlspecialchars($joke['name'], ENT_QUOTES, 'UTF-8');
echo htmlspecialchars($joke['email'], ENT_QUOTES, 'UTF-8');
?>
<input type="hidden" name="id" value="<?php echo $joke['id'];?>">
<input type="submit" value="Borrar">
?>
<br></form>
<?php endforeach; ?>
Now, the error that throws me is:
Notice: Undefined variable: jokes in C:\\xampp\\htdocs\\workspace1\\jokes.html.php on line 10
Warning: Invalid argument supplied for foreach() in C:\\xampp\\htdocs\\workspace1\\jokes.html.php on line 10
Line 10 of jokes.html.php is:
foreach($jokes as $joke):
I´m trying to get more information about foreach() but I can´t spot the error… If anyone could help me out a bit (or maybe a clue!) I would be very grateful.
Thanks!!!
Rosamunda