I’m new to PHP and working my way through Kevin Yank’s Sitepoint book (Build Your Own Database Driven Web Site using PHP and MySQL; 4th Edition).
I can create a list of all existing jokes in the database (pp.126-131), but it does not say and I cannot figure out how to list corresponding data from another field for each entry in a separate adjacent column (i.e. how to list the date of each joke alongside the text).
The code I’m using is below (using separate docs for the ‘index’ (php) and ‘jokes’ (html with php), as per Yank’s advice.
Thanks in advance for advice of what I need to include to do this,
Andy
index.php reads:
<?php
...
$result = mysqli_query($link, 'SELECT joketext FROM joke');
if (!$result)
{
$error = 'Error fetching jokes: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$jokes[] = $row['joketext'];
}
include 'jokes.html.php';
?>
jokes.html.php reads:
<!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".
xml :lang="en" lang="en">
<head>
<title>List of Jokes</title>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
</head>
<body>
<p>Here are all the jokes in the database:</p>
<?php foreach ($jokes as $joke): ?>
<p>
<?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8'); ?>
<blockquote></p>
</p></blockquote>
<?php endforeach; ?>
</body>
</html>
First, You have to alter your query to select more fields from your database/table.
In this case you’re only selecting the “joketext”.
Something like: SELECT joketext, otherfield1, otherfield2 FROM joke
Then you have to assign those field values to your jokes array:
I’ve made those changes but now it’s just presenting the last joke entry and the separate fields are presented as separate rows underneath rather than columns in the same row.
But the section of the ‘jokes.html.php’ code appears to be identical to the one I gave - have I missed the change I should be making to this?
You’re right. Only the last joke gets outputed because the jokes array gets overwritten all the time as the keys are always the same.
You’ll have to modify the jokes array to be multidimensional:
I think this might have been down to my PDO ((PHP Data Objects) not being permitted in my php.ini file. I have now permitted it and while I haven’t got the table displaying the data exactly how I want it, at least I now have a table! So I should be okay from here on in - will let you know once I have a solution.
$jokes=array(); // Setup an empty array for the jokes
while ($row = mysqli_fetch_array($result)) {
$jokes[] = $row;
}
That simplifies it, each joke is added to the $jokes array in turn.
@guruparthi; are you aware that the old mysql_* extension is depreceiated as of version 5.5 of PHP and will very likely be removed from version 5.6 of PHP? You should be using the newer mysqli_* (MySQL Improved) extension like the OP is or use PDO