Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
BOOK: PHP and MySQL: Create-Modify-Reuse ISBN: 978-0-470-19242-9
This is the forum to discuss the Wrox book PHP and MySQL: Create-Modify-Reuse by Timothy Boronczyk, Martin E. Psinas; ISBN: 9780470192429
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: PHP and MySQL: Create-Modify-Reuse ISBN: 978-0-470-19242-9 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developersí questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old March 17th, 2012, 09:13 AM
Authorized User
Points: 36, Level: 1
Points: 36, Level: 1 Points: 36, Level: 1 Points: 36, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Mar 2012
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default [SOLVED] Chapter 2 add_post.php issue

Hi there folks,

I seem to be having some issues in posting messages using this code. The add_forum.php worked without a problem, but everytime I try to post a message I get redirected to the view forum page. Nothing gets added to the database, although it does generate the error message if I leave the fields blank.

MySQL code for forum_message:

Code:
CREATE TABLE IF NOT EXISTS `ufw_forum_message` (
  `message_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `parent_message_id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `forum_id` int(10) unsigned NOT NULL,
  `user_id` int(10) unsigned NOT NULL,
  `subject` varchar(100) COLLATE latin1_general_cs NOT NULL,
  `message_text` text COLLATE latin1_general_cs NOT NULL,
  `message_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`message_id`),
  KEY `parent_message_id` (`parent_message_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COLLATE=latin1_general_cs AUTO_INCREMENT=13 ;

MySQL code for forum:

Code:
CREATE TABLE IF NOT EXISTS `ufw_forum` (
  `forum_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `forum_name` varchar(50) COLLATE latin1_general_cs NOT NULL,
  `description` varchar(100) COLLATE latin1_general_cs NOT NULL,
  PRIMARY KEY (`forum_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COLLATE=latin1_general_cs AUTO_INCREMENT=3 ;

I assume my problem is somewhere in the part of the code where its meant to update the database. I also wonder why message_date isn't included when the post is added (although its used in view)...

The code for add_post.php:
PHP Code:
<?php

// Include shared code.
// include '../lib/common.php'; -----> already included in 401.php
include '../lib/database.php';
include 
'../lib/functions.php';
include 
'../lib/class_user.php';
include 
'401.php';                                 // 401.php referenced since the user should be logged in to view this page.

// Retrieve user information.
$user User::getById($_SESSION['user_id']);
if (!
$user->user_id)
{
    die(
'<p>Sorry, you must be logged in to post.</p>');
}

// Validate incoming values.
$forum_id = (isset($_GET['fid'])) ? (int)$_GET['fid'] : 0;
$query sprintf('SELECT forum_id FROM %sforum WHERE forum_id = %d'DB_TBL_PREFIX$forum_id);
$result mysql_query($query$GLOBALS['DB']);
if (!
mysql_num_rows($result))
{
    
mysql_free_result($result);
    
mysql_close($GLOBALS['DB']);
    die(
'<p>Invalid forum id.</p>');
}
mysql_free_result($result);

$msg_id = (isset($_GET['mid'])) ? (int)$_GET['mid'] : 0;
$query sprintf('SELECT message_id FROM %sforum_message WHERE message_id = %d'DB_TBL_PREFIX$msg_id);
$result mysql_query($query$GLOBALS['DB']);
if (
$msg_id && !mysql_num_rows($result))
{
    
mysql_free_result($result);
    
mysql_close($GLOBALS['DB']);
    die(
'<p>Invalid message id.</p>');
}
mysql_free_result($result);

$msg_subject = (isset($_POST['msg_subject'])) ? trim($_POST['msg_subject']) : '';
$msg_text = (isset($_POST['msg_text'])) ? trim($_POST['msg_text']) : '';

// Add entry to the database if the form was submitted and the necessary values were supplied.
if (isset($_POST['submitted']) && $msg_subject && $msg_text)
{
    
$query sprintf('INSERT INTO %sforum_message (subject, message_text, parent_message_id, forum_id, user_id) VALUES ("%s", "%s", %d, %d, %d)'DB_TBL_PREFIXmysql_real_escape_string($msg_subject$GLOBALS['DB']), mysql_real_escape_string($msg_text$GLOBALS['DB']), $msg_id$forum_id$user->user_id);
    
mysql_query($query$GLOBALS['DB']);
    
// Redirect.
    
header('Location: view_forum.php?fid=' $forum_id . (($msg_id) ? '&mid=' $msg_id ''));
}

// Form was submitted but not all the information was correctly filled in.
else if (isset($_POST['submitted']))
{
    
$message '<p>Not all necessary information was provided. Please correct and resubmit.</p>';
}

// Generate the form.
ob_start();
if (isset(
$message))
{
    echo 
$message;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) . '?fid=' $forum_id '&mid=' $msg_id?>">
    <div>
        <label for="msg_subject">Subject:</label>
        <input type="input" id="msg_subject" name="msg_subject" value="<?php  echo htmlspecialchars($msg_subject); ?>"/><br />
        <label for="msg_text">Post Message:</label>
        <textarea id="msg_text" name="msg_text"><?php echo htmlspecialchars($msg_text); ?></textarea>
        <br />
        <input type="hidden" name="submitted" value="1"/>
        <input type="submit" value="Add Post"/>
    </div>
</form>
<?php 
$GLOBALS
['TEMPLATE']['content'] = ob_get_clean();

// Display the page.
include '../templates/basic_template.php';
?>
Any help would be greatly appreciated... and sorry about the long lines in the code
Is there any way to limit the size of the PHP box in this post?

Thanks!!

Last edited by Master Yoda; March 20th, 2012 at 06:32 AM. Reason: Solved - Solution was in the database error.
Reply With Quote
  #2 (permalink)  
Old March 17th, 2012, 10:42 PM
Authorized User
Points: 374, Level: 6
Points: 374, Level: 6 Points: 374, Level: 6 Points: 374, Level: 6
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jul 2009
Location: San Jose, Californina
Posts: 77
Thanks: 4
Thanked 6 Times in 6 Posts
Default

Hi Master Yoda,

Here is what is supposed to happen.
When you click on "Post new message.", that
will bring up the add_post.php page.
The forum id number will be on the query string;
it will look something like this:
... add_post.php?fid=48
Type in a subject and a message, then click
"Create", that will bring up the page
view.php, which will also have the forum id number on the
query string, it will look something like this:
...view.php?fid=48
You should see a link to your message listed there
right under the "Post new message" link.
If you click on that message link you should see your message
and the date stamp should be on that message.

Now, let's look at what is happening when you run your code.
You said nothing is getting added to your database.
Try adding a couple of troubleshooting print statements
to add_post.php. First, see if you get in the if block where you
do the insert. Then print out the string $query and see if it looks
like what you expect.
PHP Code:
// add entry to the database if the form was submitted and the necessary
// values were supplied in the form
if (isset($_POST['submitted']) && $msg_subject && $msg_text)

Check the result of the mysql_query that does the insert. It will
return TRUE on success and FALSE on failure.

Check the error log file.


Now, there are some mistakes in this chapter;
see these posts.

Chap 2, add_forum.php, ~$user->permission is not working properly

Chap 2, Some small errors in add_post.php and view.php

Chap 2 forums, pagination issues page 55-56

Chap 2 - Avatars and uploading files, (would apply to Chap 6 too)

The forum is working for me, so you can
get it working.

I hope this helps.
Reply With Quote
  #3 (permalink)  
Old March 18th, 2012, 05:10 AM
Authorized User
Points: 36, Level: 1
Points: 36, Level: 1 Points: 36, Level: 1 Points: 36, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Mar 2012
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi there kenj,

Thanks for the reply.

I tried getting some feedback from the script as you suggested by adding:

PHP Code:
echo $query
Which gave me a URL in the format I was expecting: add_post.php?fid=1&mid=0

and echoed:

INSERT INTO ufw_forum_message (subject, message_text, parent_message_id, forum_id, user_id) VALUES ("This is a Test Message", "This is a test.", 0, 1, 1)

which looks right to me, although I may be mistaken. I really am stumped at the moment.

About the other posts... I am aware of them, but haven't gotten as far as pagination (can't test that if I can't add messages ) or uploading avatars. I looked over your ~$user post, and you've mentioned a few interesting things, which I need to test as well. I only have one user registered at the moment for testing, and it didn't have permissions to make forums, so I modified the value in the database, although from what I can gather about some posts on further chapters, there seems to be an admin panel that should allow for assigning users certain permissions. I also need to discover where the error log should be, as I can't seem to find it on my PC (running local LAMP setup).

Thanks once again!
Reply With Quote
  #4 (permalink)  
Old March 18th, 2012, 08:43 AM
Authorized User
Points: 36, Level: 1
Points: 36, Level: 1 Points: 36, Level: 1 Points: 36, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Mar 2012
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Well, semi success. I will now need to review my view_forum.php (view.php in the book).

Something that bugged me when I exported the MySQL it had the following line:

Code:
KEY `parent_message_id` (`parent_message_id`),
and after rewriting it a few times as:

Code:
FOREIGN KEY (parent_message_id)
REFERENCES ufw_forum_message(message_id)
it kept linking back to parent_message_id instead of message_id. So I rewrite with the code the MySQL gave me, and managed to get it to link to the correct field. At least now its added to the database, and I can begin trouble shooting the view.php code!!
Reply With Quote
  #5 (permalink)  
Old March 20th, 2012, 06:39 AM
Authorized User
Points: 36, Level: 1
Points: 36, Level: 1 Points: 36, Level: 1 Points: 36, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Mar 2012
Posts: 10
Thanks: 0
Thanked 0 Times in 0 Posts
Default [SOLVED] Chapter 2 add_post.php issue

Ok... just to let anyone that has been following this thread, that the solution was in the database error. I use phpMyAdmin for working with my mySQL databases, and when adding the CREATE TABLE code, since it references a key already referenced in the previous line, it throws up a warning and apparently auto-corrects the code. This may have to do with my choice of InnoDB over MyISAM, I'm not sure. Once you point the database in the right direction, everything works well. For other fixes in this chapter, check out the links kenj posted as they are all valid!

Thanks once again.
Reply With Quote
  #6 (permalink)  
Old November 3rd, 2016, 12:40 PM
Registered User
Points: 3, Level: 1
Points: 3, Level: 1 Points: 3, Level: 1 Points: 3, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Nov 2016
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Probably I'm having the same issue, but unfortunately the author didn't explain exactly how he fixed it.

From the:
PHP Code:
    echo mysqli_error($link); 
after adding a post I'm getting this:
Code:
Cannot add or update a child row: a foreign key constraint fails (`boronczyk_2`.`FORUM_MESSAGE`, CONSTRAINT `FORUM_MESSAGE` FOREIGN KEY (`PARENT_MESSAGE_ID`) REFERENCES `FORUM_MESSAGE` (`MESSAGE_ID`))
and the post is not added to the DB.

That's the code with which I'm creating FORUM_MESSAGE table:

Code:
CREATE TABLE `FORUM_MESSAGE` (
  `MESSAGE_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `PARENT_MESSAGE_ID` bigint(20) unsigned NOT NULL DEFAULT 0,
  `FORUM_ID` int(11) unsigned NOT NULL,
  `USER_ID` int(11) unsigned NOT NULL,
  `SUBJECT` varchar(100) NOT NULL,
  `MESSAGE_TEXT` text NOT NULL,
  `MESSAGE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

  PRIMARY KEY (`MESSAGE_ID`),

  FOREIGN KEY (`USER_ID`) REFERENCES `USER`(`USER_ID`),

  FOREIGN KEY (`PARENT_MESSAGE_ID`) REFERENCES `FORUM_MESSAGE`(`MESSAGE_ID`));
I'm using phpMyAdmin. When exporting SQL I have this:

Code:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE `FORUM_MESSAGE` (
  `MESSAGE_ID` bigint(20) UNSIGNED NOT NULL,
  `PARENT_MESSAGE_ID` bigint(20) UNSIGNED NOT NULL DEFAULT '0',
  `FORUM_ID` int(11) UNSIGNED NOT NULL,
  `USER_ID` int(11) UNSIGNED NOT NULL,
  `SUBJECT` varchar(100) NOT NULL,
  `MESSAGE_TEXT` text NOT NULL,
  `MESSAGE_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `FORUM_MESSAGE`
  ADD PRIMARY KEY (`MESSAGE_ID`),  ADD KEY `USER_ID` (`USER_ID`),
  ADD KEY `PARENT_MESSAGE_ID` (`PARENT_MESSAGE_ID`);

ALTER TABLE `FORUM_MESSAGE`
  MODIFY `MESSAGE_ID` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;

ALTER TABLE `FORUM_MESSAGE`
  ADD CONSTRAINT `FORUM_MESSAGE_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `USER` (`USER_ID`),
  ADD CONSTRAINT `FORUM_MESSAGE_ibfk_2` FOREIGN KEY (`PARENT_MESSAGE_ID`) REFERENCES `FORUM_MESSAGE` (`MESSAGE_ID`);
There is ADD KEY `PARENT_MESSAGE_ID` (`PARENT_MESSAGE_ID`); (as MasterYoda mentioned as the issue), but afterwards there is also ADD CONSTRAINT `FORUM_MESSAGE_ibfk_2` FOREIGN KEY (`PARENT_MESSAGE_ID`) REFERENCES `FORUM_MESSAGE` (`MESSAGE_ID`); so I am not exactly sure if that's the problem.

Anyway I tried to add it like this
Code:
ALTER TABLE `FORUM_MESSAGE`
  ADD KEY `PARENT_MESSAGE_ID` (`MESSAGE_ID`);

ALTER TABLE `FORUM_MESSAGE`
  ADD CONSTRAINT `FORUM_MESSAGE_ibfk_2` FOREIGN KEY (`PARENT_MESSAGE_ID`) REFERENCES `FORUM_MESSAGE` (`MESSAGE_ID`);
But that didn't work.

That's my add_post.php If you would need it:
PHP Code:
<?php

require_once '../lib/DBconn.php';
require_once 
'../lib/functions.php';
require_once 
'../lib/User.php';
require_once 
'401.php';

$user User::getById(($_SESSION['userId']));

$forum_id = (isset($_GET['fid'])) ? intval($_GET['fid']) : 0;

$query "SELECT FORUM_ID FROM FORUM WHERE FORUM_ID = '$forum_id'";

$conn DB::connect();

$result $conn->query($query);

if (!
mysqli_num_rows($result)) {
    
    
mysqli_free_result($result);
    die(
"<p>Incorrect forum ID.</p>");
}

mysqli_free_result($result);

$msg_id = (isset($_GET['mid'])) ? intval($_GET['mid']) : 0;

$query "SELECT MESSAGE_ID FROM FORUM_MESSAGE WHERE MESSAGE_ID = '$msg_id'";

$conn DB::connect();

$result $conn->query($query);

if (
$msg_id && !mysqli_num_rows($result)) {
    
    
mysqli_free_result($result);
    die(
"<p>Incorrect message ID.</p>");
}

mysqli_free_result($result);

$msg_subject = (isset($_POST['msg_subject'])) ? trim($_POST['msg_subject']) : '';
$msg_text = (isset($_POST['msg_text'])) ? trim($_POST['msg_text']) : '';

if (isset(
$_POST['submitted']) && $msg_subject && $msg_text) {
    
    
$conn DB::connect();
    
$msub mysqli_real_escape_string($conn$msg_subject);
    
$mtxt mysqli_real_escape_string($conn$msg_text);
    
$uid $user->getUid();
    
    
$query "INSERT INTO FORUM_MESSAGE (SUBJECT, MESSAGE_TEXT, PARENT_MESSAGE_ID, FORUM_ID, USER_ID) VALUES ('$msub', '$mtxt', '$msg_id', '$forum_id', '$uid')";
    
    
    
$conn->query($query);
    echo 
mysqli_error($conn);
    
    
// redirection
    
    //header('Location: view.php?fid=' . $forum_id . (($msg_id) ? '&mid=' . $msg_id : ''));
    
// form sent but incorret data was given
} elseif (isset($_POST['submitted'])) {
    
    
$message "<p>Not all necessary dava was given. Please fill the form and send it again</p>";
}

ob_start();

if (isset(
$message)) echo $message;
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) . '?fid=' $forum_id '&mid=' $msg_id?>" method="POST">
    <div>
        <label>Subject</label><br>
        <input type="input" name="msg_subject" id="msg_subject" value="<?php echo htmlspecialchars($msg_subject); ?>"><br>
        <label>Message</label><br>
        <input type="input" name="msg_text" id="msg_text" value="<?php echo htmlspecialchars($msg_text); ?>"><br><br>
        <input type="submit" value="Create"><br><br>
        <input type="hidden" name="submitted" value="1">
    </div>
</form>

<?php

$GLOBALS
['TEMPLATE']['content'] = ob_get_clean();

include 
'../templates/template.php';
I would really appreciate any help :D
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Chap 2, Some small errors in add_post.php and view.php kenj BOOK: PHP and MySQL: Create-Modify-Reuse ISBN: 978-0-470-19242-9 0 October 22nd, 2009 07:48 PM
Chapter 13-index.php issue Swilling BOOK: Beginning PHP5, Apache, and MySQL Web Development ISBN: 978-0-7645-7966-0 0 February 24th, 2009 11:15 PM
begin php & mysql - chapter 12, user_form.php jon_stubber Beginning PHP 1 March 9th, 2006 09:57 AM
Chapter 10 charedit.php issue luke adamis BOOK: Beginning PHP5, Apache, and MySQL Web Development ISBN: 978-0-7645-7966-0 0 January 1st, 2006 05:28 PM
PHP/Design issue wolftrap1 BOOK: Beginning PHP4/PHP 5 ISBN: 978-0-7645-4364-7; v5 ISBN: 978-0-7645-5783-5 4 February 4th, 2004 08:53 PM



All times are GMT -4. The time now is 04:40 PM.


Powered by vBulletin®
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.