PHP for Absolute Beginners-source code error..please help

Hello all,

I am trying to improve my php skills and thought I would start with PHP for Absolute Beginners. I am going through the examples, and have come to a problem in Chapter 6. The exact output that I am trying to get is that on page 183. For those of you without the book, i will provide a description and some code that I am using. I have been troubleshooting this for hours, and would sure appreciate some help.

What I have is a simple form that takes input from the user and creates a title and an entry. The ultimate goal I am trying to accomplish is to have the list of entries show on the main page, and for the title and entries to appear when you click on the link of the title.

Everything was working just fine when I was working with just the id…when I started to pass information to the page is when things started to not work properly. I have the exact same code as the book, so I don’t know what is wrong. When you load the main page, the list of entries for page blog appears…but when you click on the link, the fulldisp is not set to the value to echo the proper entries. Instead, it refreshed the page with the same information as you first browse the main page. Here are my various files.

form
admin.php


<?php
if(isset($_GET['page']))
{
$page = htmlentities(strip_tags($_GET['page']));
}
else
{
$page = 'blog';
}
?>
<!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>
<meta http-equiv="Content-Type"
content="text/html;charset=utf-8" />
<link rel="stylesheet"
href="/simple_blog/css/default.css" type="text/css" />
<title> Simple Blog </title>
</head>
<body>
<h1> Simple Blog Application </h1>
<form method="post" action="/simple_blog/inc/update.inc.php">
<fieldset>
<legend>New Entry Submission</legend>
<label>Title
<input type="text" name="title" maxlength="150" />
</label>
<label>Entry
<textarea name="entry" cols="45" rows="10"></textarea>
</label>
<input type="hidden" name="page"
value="<?php echo $page ?>" />
<input type="submit" name="submit" value="Save Entry" />
<input type="submit" name="submit" value="Cancel" />
</fieldset>
</form>
</body>
</html>

Main Page
index.php


<?php
/*
* Include the necessary files
*/
include_once 'inc/functions.inc.php';
include_once 'inc/db.inc.php';
// Open a database connection
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
// Determine if an entry ID was passed in the URL
if(isset($_GET['page']))
{
$page = htmlentities(strip_tags($_GET['page']));
}
else
{
$page = 'blog';
}
$id = (isset($_GET['id'])) ? (int) $_GET['id'] : NULL;
// Load the entries
$e = retrieveEntries($db,$page,$id);
// Get the fulldisp flag and remove it from the array
$fulldisp = array_pop($e);
// Sanitize the entry data
$e = sanitizeData($e);
?>
<!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>
<meta http-equiv="Content-Type"
content="text/html;charset=utf-8" />
<link rel="stylesheet" href="/css/default.css" type="text/css" />
<title> Simple Blog </title>
</head>
<body>
<h1> Simple Blog Application </h1>
<div id="entries">
<?php
// If the full display flag is set, show the entry
if($fulldisp==1)
{
?>
<h2> <?php echo $e['title'] ?> </h2>
<p> <?php echo $e['entry'] ?> </p>
<p class="backlink">
<a href="./">Back to Latest Entries</a>
</p>
<?php
} // End the if statement
// If the full display flag is 0, format linked entry titles
else
{
// Loop through each entry
foreach($e as $entry) {
?>
<p>
<a href="?id=<?php echo $entry['id'] ?>">
<?php echo $entry['title'] ?>
</a>
</p>
<?php
} // End the foreach loop
} // End the else

?>
<p class="backlink">
<a href="/simple_blog/admin.php?page=<?php echo $page ?>">Post a New Entry</a>
</p>
</div>
</body>
</html>

Update file-updates entries in mysql database and also takes user to submitted page…but doesn’t???


<?php
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Save Entry'
&& !empty($_POST['page'])
&& !empty($_POST['title'])
&& !empty($_POST['entry']))
{
// Include database credentials and connect to the database
include_once 'db.inc.php';
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
// Save the entry into the database
$sql = "INSERT INTO entries (page, title, entry)
VALUES (?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute(
array($_POST['page'],$_POST['title'],$_POST['entry'])
);
$stmt->closeCursor();
// Sanitize the page information for use in the success URL
$page = htmlentities(strip_tags($_POST['page']));
// Get the ID of the entry you just saved
$id_obj = $db->query("SELECT LAST_INSERT_ID()");
$id = $id_obj->fetch();
$id_obj->closeCursor();
// Send the user to the new entry
header('Location: /simple_blog/?page='.$page.'&id='.$id[0]);
exit;
}
else
{
header('Location: ../');
exit;
}
?>

Functions file…retrieves data
functions.inc.php


<?php
function retrieveEntries($db, $page, $url=NULL)
{
/*
* If an entry ID was supplied, load the associated entry
*/
if(isset($id))
{
$sql = "SELECT title, entry
FROM entries
WHERE id=?
LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
// Save the returned entry array
$e = $stmt->fetch();
// Set the fulldisp flag for a single entry
$fulldisp = 1;
}
/*
* If no entry ID was supplied, load all entry titles
*/
else
{
$sql = "SELECT id, page, title, entry
FROM entries
WHERE page=?
ORDER BY created DESC";
$stmt = $db->prepare($sql);
$stmt->execute(array($page));
$e = NULL; // Declare the variable to avoid errors
// Loop through returned results and store as an array

/*foreach($db->query($sql) as $row){
$e[] = array(
'id' => $row['id'],
'title' => $row['title']);
}*/
$fulldisp = 0;
}
while($row = $stmt->fetch()) {
$e[] = $row;
}
// Set the fulldisp flag for multiple entries


/*
* If no entries were returned, display a default
* message and set the fulldisp flag to display a
* single entry
*/

if(!is_array($e))
{
$fulldisp = 1;
$e = array(
'title' => 'No Entries Yet',
'entry' => '<a href="/simple_blog/admin.php">Post an entry!</a>'
);
}

// Add the $fulldisp flag to the end of the array
array_push($e, $fulldisp);
return $e;
}
function sanitizeData($data)
{
// If $data is not an array, run strip_tags()
if(!is_array($data))
{
// Remove all tags except <a> tags
return strip_tags($data, "<a>");
}
// If $data is an array, process each element
else
{
// Call sanitizeData recursively for each array element
return array_map('sanitizeData', $data);
}
}

?>

I would appreciate any recommendations. I believe there is a serious error with the source code that the book provides. Consider this a challenge to finding the error and why it is causing so much havoc on an absolute beginner! It is a beginners book! :lol:

Try changing

header('Location: /simple_blog/?page='.$page.'&id='.$id[0]);

in

header('Location: /simple_blog/index.php?page='.$page.'&id='.$id[0]);

Thank you for the suggestion. That is a great idea to pass in the index.php page but unfortunately, that does not fix the problem.


<form method="post" action="/simple_blog/inc/update.inc.php">

that looks suspicious to me, you would not normally link directly to an inc (include) file.

You can name files what you want of course … but generally your *.inc.php files are embedded in another file. Try looking at that line a bit more closely.

In case you are losing your sanity, create a file called:

test.php


<?php
var_dump($_POST);
?>

and put that in the action;


<form method="post" action="/simple_blog/test.php">

Then you will at least have proven to yourself:

a) you are not going nuts
b) the HTML of your form is well-formed
c) PHP is getting the values you expected and at least something works

Its about slowly getting control of the situation, and starting to get things to string together in your brain instead of just following the book by rote. We’ve all been there.

Thanks for the input!

The result actually returned array(0) {}

I will continue to search through my code and find out what is wrong. Things are starting to string in my head. If I can figure out why this caused me a problem, then I can learn from it!

Any suggestions on where to correct this error will be appreciated. I will give it go myself and will post if I find a solution.

I was testing that last suggestion wrong. I when I submit a form on http://localhost/simple_blog/admin.php and then navigate to http://localhost/simple_blog/test.php, the array reads:

array(4) [“title”]=> string(4) “Help” [“entry”]=> string(7) “Help Me” [“page”]=> string(4) “blog” [“submit”]=> string)10) “Save Entry”}

The book says to pass the url into the function retrieveEntries. This looks like this:


function retrieveEntries($db, $page, $url=NULL)

I changed to this


function retrieveEntries($db, $page, $id)

I also found a misplaced bracket before the fulldisp=0 in the functions.inc.php file. I changed the bracket to put the $fulldisp=0 inside the else so it does not get set to it automatically by default later on in the script.

It was unfortunate that the author provided source code that did not work. However, as previously mentioned, we must get a idea on how the code works in our head and not just follow the book…even though following the book is where someone needs to start. Working through to find this solution helped me feel more confident about what I am doing and how to test for errors! Yay! :slight_smile:

I look forward to growing in my knowledge in php programming. Thanks everyone!

Glad it worked out for you in the end, well done for sticking with it.

Debugging will no doubt become part of your life until you determine to write small iterations of code, testing as you go - so if you do come across a sudden error you can be confident it was something you did in last few minutes. Having a good text editor with multiple undo/redo is a godsend when it comes to working in this fashion.

There are lots of simple debugging tricks you should adopt as you go along all of which allow you to “peek inside” what PHP is doing at your behest.

[google]simple debugging techniques php[/google]