PHP undefined variable when I try to extract data from database

Panha Phal

So I got these issues when I tried to extract data from the database. My DB connection is working fine. It is showing "Database connection established" and inside my index.php I wrote a for each loop to get the data and inside my HTML code, I display it inside the table. I got these errors:


Notice: Undefined variable: jokes in C:\xampp\htdocs\comp1321_database\jokes\jokes.html.php on line 16

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\comp1321_database\jokes\jokes.html.php on line 16

Here is the HTML and php code to display the data:

<?php include_once 'admin/includes/helpers.inc.php';?>

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="utf-8">
     <title>List of Jokes</title>
</head>
<body>
<p><a href ="/comp1321_database/jokes/form.html.php/">Add your own joke</a></p>     
<p>Here are all the jokes in the database</p>
<!-- into a table -->
        <table border="1">
        <?php foreach ($jokes as $joke): ?>
            <!-- <form action="?deletejoke" method="post">  -->
             <tr>
             <td><?php html($joke['joketext']);?></td>
             <td><?php $display_date = date("D d M Y", strtotime($joke['jokedate']));
             html($display_date); ?>
         </td>
         <td><img height="100px" src="images/<?php html($joke['image']);?>"
            /></td>
            <td><input type="hidden" name="id" value="<?php echo $joke['id'];
            ?>">
            <input type="submit" value="Delete"></td>
        </tr>
    <!-- </form> -->
        <?php endforeach; ?>
        </table>
   <?php include 'admin/includes/footer.inc.html.php';?>   
</body>
</html>   

and here is the index.php:



<?php
// selection block
include  'admin/includes/db.inc.php';
// 
try
{
    $sql = 'SELECT * FROM joke';
    $result = $pdo->query($sql);

}  catch (PDOException $e) {
    $error = 'Error fetching jokes' . $e->getMessage();
    include 'error.html.php';
    exit();
}
foreach ($result as $row) {
    $jokes[] = array(
        'joketext'=> $row ['joketext'],
        'jokedate'=> $row['joketext'],
        'image'=> $row['image']
    );

}
 include 'jokes.html.php';
?>

Many thanks.

Wesley Smith

Initialize your jokes variable before you try to use it, ie:

$jokes = [];

try
{
    $sql = 'SELECT * FROM joke';
    $result = $pdo->query($sql);

}  catch (PDOException $e) {
    $error = 'Error fetching jokes' . $e->getMessage();
    include 'error.html.php';
    exit();
}
foreach ($result as $row) {
    $jokes[] = array(
        'joketext'=> $row ['joketext'],
        'jokedate'=> $row['joketext'],
        'image'=> $row['image']
    );

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive