Jump to content

Need help with templates


vipsa
Go to solution Solved by mac_gyver,

Recommended Posts

I am a newbie and I have a few questions please:

 

1. I am trying to get data from a database and display it in a template. So I have created all the connection things and they work and I have created a while loop to loop through the result set and here is the code

 

<code>

while ($row = $result->fetch())
{
$jokes[] = $row['joketext'];
}
include 'jokes.html.php';
</code>
 
But when you go to jokes.html.php then it tells you that the array $jokes is undefined.
 
My questions is this:

If I create a php file and I create variables or set variables and I then import a template file "Are the variables then availablle to the template file I import?
 
Here is the code for the template file
 
</code>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>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>
 
</code>
 
Any help is appreciated

 

Link to comment
Share on other sites

there's nothing technically wrong with the snippets of code you posted, provided they are in the same program scope, the loop is actually fetching the data into the $jokes array, and your code is not clearing the $jokes array between where it is being loaded and where it is being used.

 

is the code you posted your actual code and have you confirmed that $jokes actually contains the expected result from the while(){} loop?

Link to comment
Share on other sites

The table contains three rows

This is a joke

Two men are sitting in a bar

The blond parks her car

 

 

Here is all the php code for the connection script which if ran on it's own works fine. But when I include a template page then the page says variable undefined. So how do I get the template page to use the $jokes array?

 

<code>

<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=learnphp', 'corne',
'lekker1');
$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 jokes';
$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';
</code>
 
 
and the page supposed to show the results the code is in my first post.
Edited by vipsa
Link to comment
Share on other sites

That code is fine. The try/catch statments will catch any errors from PDO/Database and display the error. The while loop will populate the $results array with the jokes if the query executed ok.
 
The only time you'll get the Undefined variable: jokes in path/to/jokes.html.php error is if your query is returning no results, because there is no entries in the jokes table or when you physically access that file, ie http://site.com/jokes.html.php. This is because the $jokes array is defined in the file that was including jokes.html.php. The $jokes array is not remembered.

Link to comment
Share on other sites

I'm sorry but this does not answer my question because why would someone writing a book have code like this if it does not work and I have seen this before so why would the while loop include a file if the variable is not available to the file that is being included?

 

There are results and if you run the code that is in the database connection script it displays the results fine. It is when you want to display the results on another page jokes.html.php when the problem starts for me

Link to comment
Share on other sites

again, there is nothing technically wrong with the code, provided the query is working and the code, especially the file name in the include statement, is the actual code,

 

what is the exact error message you got?

 

you also never confirmed that you actually have checked in your program that the $jokes array contains the expected data. in programming you cannot ASSUME anything when you don't get the expected results, you must actually check what the data is and confirm it, in multiple places, as needed, to pin down where it is working and at what point it is not working.

Edited by mac_gyver
Link to comment
Share on other sites

There are 2 files

 

database.php

jokes.html.php

 

there is a database learnphp with a tables jokes and WITH RECORDS INSIDE THE TABLE

 

I want to display the records on the jokes.html.php page

 

If I run database.php alone then it works fine and I see the results

 

If I open jokes.html.php then I get  variable $jokes undefined and a Warning: Invalid argument supplied for foreach() in C:\wamp\www\learnphp\jokes.html.php on line 12

 

Here is the code for both files:

 

DATABASE.PHP:

 

<?php

try
{
$pdo = new PDO('mysql:host=localhost;dbname=learnphp', 'corne',
'lekker1');
$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 jokes';
$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';
 
 
HERE IS THE CODE FOR JOKES.HTML.PHP:
 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Jokes</title>
</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): 
    ?>
<blockquote>
<p><?php 
echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8');
?>
</p>
</blockquote>
<?php endforeach; ?>
</body>
</html>
 
 

Now can someone please tell me what is wrong and what I need to do to fix this. I will be very grateful if I could get a clear answer explaining how this is supposed to work Thank you

Link to comment
Share on other sites

  • Solution
If I run database.php alone then it works fine and I see the results

 

 

it works because database.php is including the template file - include 'jokes.html.php'; that's the way it is supposed to work.

 

you are not supposed to browse directly to jokes.html.php. it's not a complete web page. it is only the template file that uses the $jokes array. it is only supposed to be included into the file where the $jokes array is being produced.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.