Selecting Data from DB and Adding Data to DB via Form

Hey All,

Having a bit of a problem figuring out how-to get a form to work. Little bit of context: There are eBooks / titles and there are pages that belong to these eBooks. Just pages of plain text. So, I have a “books” table that contains bookID (primary key), bookTitle, and a few other fields like book description and some foreign keys for the author, publisher, etc. I have another table called “pages” that contains pageID (primary key), pageText, pageSlug and bookID (foreign key).

I want to use a form on a web page to add a page of text to a particular book. So, there’s a drop-down box where you can select the title / eBook you want to add the page of text to, a text field for entering the pageSlug (which is actually the real page number) and a textarea for adding the actual page content to pageText.

Firstly, the drop-down box isn’t retrieving the existing bookTitles from the books table and it basically continues to go down hill from there :stuck_out_tongue: The code I have, I’ve taken from Kevin Yank’s PHP & MySQL: Novice to Ninja book, and edited it slightly for my particular needs, so that may be why it isn’t working…But if I could ask you guys for a little bit of help on why it’s not working and how-to get it working then that’d be great!

Here’s the code I’ve got!

pages.html


<?php include $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta name="description" content="Description unavailable.">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Add Pages</title>
		<!--[if lt IE 9]>
		<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->
		<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
		<link rel="stylesheet" media="screen" href="../../css/stylesheet.css">
	</head>
	
	<body>
		<article>
			<header>
				<h1>Add Pages</h1>
			</header>
			
			<div id="content">
				<form action="?" method="post">

					<div>
						<label for="book">eBook Title:</label>
						<select name="book" id="book">
							<option value="">Select Title</option>
							<?php foreach ($books as $book): ?>
								<option value="<?php htmlout($book['id']); ?>">
									<?php htmlout($book['title']); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>

					<div>
						<label for="pageslug">Page Number:</label>
						<input type="text" id="pageslug" name="pageslug"/>
					</div>

					<div>
						<label for="pagetext">Page Text:</label>
						<textarea id="pagetext" name="pagetext" rows="10" cols="40"><?php htmlout($content); ?></textarea>
					</div>

					<div>
						<input type="hidden" name="id" value="<?php htmlout($id); ?>" />
						<input type="submit" value="Add Page">
					</div>

				</form>
			</div>
		</article>
	</body>
</html>


<?php
include $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';

if (isset($_GET['add']))
{
  include $_SERVER['DOCUMENT_ROOT'] . '/includes/dbconnection.inc.php';

  // Build the list of books
  try
  {
    $result = $pdo->query('SELECT bookID, bookTitle FROM books');
  }
  catch (PDOException $e)
  {
    $error = 'Error fetching list of books.';
    include 'error.html.php';
    exit();
  }

  foreach ($result as $row)
  {
    $books[] = array('bookID' => $row['id'], 'bookTitle' => $row['title']);
  }

  include $_SERVER['DOCUMENT_ROOT'] . '/includes/dbconnection.inc.php';

  if ($_POST['book'] == '')
  {
    $error = 'You must choose a book for this page.
        Click &lsquo;back&rsquo; and try again.';
    include 'error.html.php';
    exit();
  }

  try
  {
    $sql = 'INSERT INTO pages SET
        pagetext = :pagetext,
        pageslug = :pageslug,
        bookID = :bookID';
    $s = $pdo->prepare($sql);
    $s->bindValue(':pagetext', $_POST['text']);
    $s->bindValue(':pageslug', $_POST['slug']);
    $s->bindValue(':bookID', $_POST['book']);
    $s->execute();
  }
  catch (PDOException $e)
  {
    $error = 'Error adding new page.';
    include 'error.html.php';
    exit();
  }

  $pageID = $pdo->lastInsertId();

	header('Location: .');
	exit();
}

include 'pages.html.php';

And the error.html.php is just the same as pages.html, with the exception that all of the PHP code is replaced by

echo $error

.

This is what the page looks like curently:

Any ideas or pointers? Greatly appreciated, as always. :slight_smile:

Hi Andrew,

Try this:



// 1. add this debugging script to the top of your first called page:
   error_reporting(-1); ini_set('display_errors',1);

   //======================================
   function dBug($var='No paramereter passed???', $title = 'No Title???')
   {
     echo '<pre style="background-color: pink">';
         echo $title .' => ';
         print_r($var);
     echo '</pre>';
   }

// 2.  Change these two lines:
     // if (isset($_GET['add']))          // ORIGINAL
     if (isset($_POST['addPage'])) 
    {
      ...
    }

// 3 . Change pages.html.php -> form method to post:
        <form action="?" method="post">

// 4.  Add submit name='addPage'
        <input type="submit" name="addPage" value="Add Page">

// 5. Add debugging script to pages.html.php
  <body>
    <h4>
        <?php dBug($_GET, '$_GET'); dBug($_POST, '$_POST'); dBug($books, 'books'); ?>
    </h4>  


Hey John, thanks for the quick response! I’ve done as you suggested and this is the result:

I’ve got no idea what that’s telling me though - I hope it gives you some useful information on the problem?

Your “Attachments Pending Approval”.

Is it possible to cut and paste the error messages?

Your first Attachment is now visible…

The message “undefined variable - content”.

You need to add content to $sql statement and also add it to the $books array:

 

    // $sql = 'SELECT bookID, bookTitle FROM books'; 
    $sql = 'SELECT bookID, bookTitle, bookContent FROM books'; // ADDED bookContent
    $result = $pdo->query($sql); 
    ...
    ...
    ...
    $books[] = array
    (
      'bookID'           => $row['id'],
      'bookTitle'       => $row['title'],
      'bookContent' => $row['content'],
    ); 



// page.html.php
   <textarea id="pagetext" name="pagetext" rows="10" cols="40">
         <?php htmlout($book['bookContent']); ?>
   </textarea>


Might be better to just link you to an external image of it rather than cut and paste the error message, see here: http://i.imgur.com/cyhxygK.png

But that means adding bookContent to the books table…

The pageText / $content in the textarea is where the person adds the page text for the book, this goes into the pageText field in the pages table in the DB. All I want to select from the DB on this form is a list of all book titles in the books table and display it in the drop-down selection. The pageSlug and pageText is entered manually and once the person hits the Add Page button the form should add a new record in the pages table with a new pageID auto generated, the pageSlug entered and pageText entered along with a number for the corresponding bookID.

OK, I can see it now.

Try this:



  // page.htnl.php
  <body>
    <h4>
        <?php 
           dBug($_GET, '$_GET'); 
           dBug($_POST, '$_POST'); 

          if( isset($books)
          {
           dBug($books, 'books');
          }else{
             echo 'There are no books - please check $sql'; 
          }
        ?>
    </h4>  


Ok…Well this is certainly interesting! Apparently there are no books and I need to check the $sql…Hmmm, so it’s narrowed the problem down to the SQL then.


But the SQL for the other pages that work perfectly fine is the same! How can there be an issue on this page when it’s the same code?!

Hi Andrew,

I do not have “Kevin Yank’s PHP & MySQL: Novice to Ninja book” so debugging is not easy.

I would suggest replacing the two files with the original scripts and starting again.

I would keep the function dBug(…) and ensure that the table books data is available before proceeding onto the next error.