PHP fetch function can not display my arrays

Hi everyone, this is Kasule once more…i have made great steps in my learnin but my code is not producing the expected output. below is are the jokes.html.php and index.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>The List Of Jokes</title>
    </head>
    <body>
        <p>Here are all the jokes in the database:</p>
        <?php foreach ($jokes as $joke): ?>
        <blockquote>
            <p><?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8');
                ?>
            </p>
        </blockquote>
        <?php endforeach; ?>
    </body>
</html>
<?php
try
{
    $pdo = new PDO('mysql:host=localhost;dbname=ijdb','suleiman','P@ss@123');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec('SET NAMES "utf8"');
}
catch(PDOException $e)
{
    $error = 'Unable to connect to the database server.';
    include 'error.html.php';
    exit();
}
try
{
    $sql =  'SELECT joketext FROM joke';
    $result = $pdo->query($sql);
}
catch(PDOException $e)
{
    $error = 'Error fetching jokes:' . $e->getMessage();
    include 'error.html.php';
    exit();
}
while ($row = $result->fetch());
{
    $jokes[] = $row['joketext'];
}
include 'jokes.html.php';''

the only output i get is this:
‘’‘Here are all the jokes in the database:’‘’

Not an expert but why you using : after condition and where are the { } brackets?. and is endforeach necessary?

The colon ( : ) is used in place of the opening bracket in this case. It allows html to go within the condition when the php tag closes.
The endforeach is there in place of the closing bracket.

@kasule I don’t see any glaring error in the code.
You don’t see any errors reported?
A silly question, but I have to ask, did you put any jokes into the table?

2 Likes

Yes @SamA74, i already have jokes in the table

Try removing the semicolon after the $result->fetch())

3 Likes

Thanks @John_Betong, the problem is sorted

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.