Undefined Variable error

I’m studying BYO database driven website by kevin yank pg 158-162 “Select with multiple tables” section. I have simply copied everything according to the book and when I run the page it’s giving me an error saying; “Undefined variable error…”. When I check the path to the line where the problem is i still feel the variable has been defined… I’m stuck! code below for both the Dom & php script:

//…THE DOM

<!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”>
<head>
<title>List/delete of jokes</title>
<meta http-equiv=“content-type” content=
“text/html; charset=utf-8” />
</head>
<body>
<p><a href=“?addjoke”>Add you 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>

//…PHP SCRIPT

<?php
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map(‘stripslashes_deep’, $value) :
stripslashes($value);

	return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);

}

if (isset($_GET['addjoke'])) {
	include 'form.html.php';
	exit();
}

// establishing connection with database
$link = mysqli_connect(‘localhost’, ‘root’);
if (!$link) {
$error = ‘Unable to connect to the server.’;
include ‘error.html.php’;
exit();
}
if (!mysqli_set_charset($link, ‘utf8’)) {
$output = ‘Unable to set database connection encoding.’;
include ‘output.html.php’;
exit();
}
if (!mysqli_select_db($link, ‘ijdb’)) {
$error = ‘Unable to locate the Joke database.’;
include ‘error.html.php’;
exit();
}

if (isset($_POST[‘joketext’])) {
$joketext = mysqli_real_escape_string($link, $_POST[‘joketext’]);
$sql = ‘INSERT INTO joke SET
joketext = "’ . $joketext . ‘",
jokedate = CURDATE()’;
if (!mysqli_query($link, $sql)) {
$error = 'Error adding submitted joke: ’ . mysqli_error($link);
include ‘error.html.php’;
exit();
}
header(‘Location: .’);
exit();
}

$result = mysqli_query($link, ‘SELECT joke.id, joketext, name, email
FROM joke INNER JOIN author ON authorid = author.id’);
if (!$result) {
$error = 'Error fetching jokes: ’ . mysqli_error($link);
include ‘error.html.php’;
exit();
}

while ($row = mysqli_fetch_array($result)) {
$jokes[] = array(‘id’ => $row[‘id’], ‘text’ => $row[‘joketext’],
‘name’ => $row[‘name’], ‘email’ => $row[‘email’]);
}
include ‘jokes.html.php’;
?>

//this is the error

[COLOR=“Red”]Notice: Undefined variable: jokes in C:\wamp\www\sitepoint\jokes\jokes.html.php on line 12

Warning: Invalid argument supplied for foreach() in C:\wamp\www\sitepoint\jokes\jokes.html.php on line 12[/COLOR]

please use the

 tags when posting code. ;)
//....THE DOM

<!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">
<head>
<title>List/delete of jokes</title>
<meta http-equiv="content-type" content=
"text/html; charset=utf-8" />
</head>
<body>
    <p><a href="?addjoke">Add you 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>

//....PHP SCRIPT

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value) {
        $value = is_array($value) ?
            array_map('stripslashes_deep', $value) :
            stripslashes($value);
            
        return $value;
    }
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}

    if (isset($_GET['addjoke'])) {
        include 'form.html.php';
        exit();
    }

// establishing connection with database
$link = mysqli_connect('localhost', 'root');
if (!$link) {
    $error = 'Unable to connect to the server.';
    include 'error.html.php';
    exit();
}
if (!mysqli_set_charset($link, 'utf8')) {
    $output = 'Unable to set database connection encoding.';
    include 'output.html.php';
    exit();
}
if (!mysqli_select_db($link, 'ijdb')) {
    $error = 'Unable to locate the Joke database.';
    include 'error.html.php';
    exit();
}


if (isset($_POST['joketext'])) {
    $joketext = mysqli_real_escape_string($link, $_POST['joketext']);
    $sql = 'INSERT INTO joke SET
        joketext = "' . $joketext . '",
        jokedate = CURDATE()';
    if (!mysqli_query($link, $sql)) {
        $error = 'Error adding submitted joke: ' . mysqli_error($link);
        include 'error.html.php';
        exit();
    }
    header('Location: .');
    exit();
}

$result = mysqli_query($link, 'SELECT joke.id, joketext, name, email 
    FROM joke INNER JOIN author ON authorid = author.id');
if (!$result) {
    $error = 'Error fetching jokes: ' . mysqli_error($link);
    include 'error.html.php';
    exit();
}

$jokes=array();
while ($row = mysqli_fetch_array($result)) {
    $jokes[] = array('id' => $row['id'], 'text' =>  $row['joketext'], 
    'name' => $row['name'], 'email' => $row['email']);
}
include 'jokes.html.php';
?>

The error comes about because the foreach loop expects to be given an array of jokes but when there are no jokes found then it is given an empty $jokes variable. The bit of code that I added:

$jokes=array();

This defines $jokes as an empty array so that if there are no jokes the foreach is given an empty array, if there are jokes then they are added to the array as normal.

Tried to put the empty array and no error in sight but… there are no jokes from the database displayed… what then? The table surely contains some jokes …

Do you have PHPMyAdmin available? If so try the query in there (against the database) to check that the query returns what you expect it to return

Well tried to query the database from MySql console and it throws an error to say: “empty set (0.00 sec)” Here’s the code:

SELECT joke.id, LEFT(joketext, 20), name, email
FROM joke INNER JOIN author
ON authorid = author.id;

On the other hand I am able to query both tables to see if they contain anything… yes they do (does the error suggest there’s nothing in the tables?) I’m confused! :confused:

can you do a basic “SELECT joke.id FROM joke WHERE 1”

substituting this simple query for your more complex query would help you identify if the query is the root of the problem or not.

yes, I’ve tried the simple query “SELECT joke.id FROM joke WHERE 1” and it’s returned the ID column from the jokes table…

Try:


SELECT
         joke.id
      , LEFT(joketext, 20)
      , name
      , email
FROM
     joke
INNER JOIN
     author
ON
     joke.authorid = author.id;

MySQL knew that you wanted to use the ID field in the author table but it didn’t know that you wanted to use the authorid field in the joke table as the table was not specified.

…rest of query
ON
table_name_one.fieldname = table_two_name.fieldname

Experimenting with your suggested query directly in mysql console I found out that I’d added a little more jokes with no corresponding author hence there had to be empty set error as my query tried to retrieve each joke in conjunction with the author therefore the one joke with no author caused the query to return “empty set”.

I simply updated both tables (author & jokes) the rest just fell into place… thanks for that - back in business!!