php mysql novice to ninja 5th edition
After following the steps I keep getting the error:
Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/ijdb/admin/authors/authors.html.php on line 13
Does anyone know where I went wrong or where the book went wrong, here's the code:
<?php include_once $_SERVER['DOCUMENT_ROOT'] .
<p><a href="?add">Add new author</a></p>
<?php foreach ($authors as $author): ?>
<form action="" method="post">
<?php htmlout($author['name']); ?>
<input type="hidden" name="id" value="<?php
echo $author['id']; ?>">
<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Delete">
<?php endforeach; ?>
<p><a href="..">Return to JMS home</a></p>
That error means that the foreach loop was expecting to be given an array to loop through but was given something else. Whenever you're going to build an array of items that a foreach is going to work with always do:
That ensures that the variable is set up as an array, if nothing is in it the foreach will see an empty array
I'm a complete newbie at this, and I'm working off the code in the book. Would it be possible for you to rewrite the code so it'll work. If you could I'd really appreciate it and hopefully I'll be able to understand.
Okay, I need you to confirm this but does your '/ijdb/includes/helpers.inc.php' file have something like the following:
// Display author list
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
$result = $pdo->query('SELECT id, name FROM author');
catch (PDOException $e)
$error = 'Error fetching authors from the database!';
foreach ($result as $row)
$authors = array('id' => $row['id'], 'name' => $row['name']);
If so, you need to add the following immediately before the foreach
$authors = array();
I'm a bit surprised that the book has this typo in it. Granted you would only see this Warning if you have PHP setup to show warnings (which is good! I prefer new users have PHP setup to show warnings and notices when learning, you'll learn better practices that way).
lol, not even close all it has is:
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
Okay, what file has the foreach statement that builds $authors? You will want to add $authors = array(); immediately above the foreach to get rid of the warning.
Does the book expect you to have already put data into the authors table? Have you skipped a step?
Ah, sorry, I found it, the file name would be: chapter7/admin/authors/index.php
Adding $authors = array(); before the foreach will remove the warning.
I think either way, he would run into this as throughout the process you create INSERT, UPDATE, and DELETE actions. So after you delete all authors you will see the warning.
Thanks for the help guys, you helped me big time with my own similar problem in a roundabout way
This topic is now closed. New replies are no longer allowed.