p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/)
-   BOOK: PHP and MySQL: Create-Modify-Reuse ISBN: 978-0-470-19242-9 (http://p2p.wrox.com/book-php-mysql-create-modify-reuse-isbn-978-0-470-19242-9-406/)
-   -   Chapter 2 add_post.php issue (http://p2p.wrox.com/book-php-mysql-create-modify-reuse-isbn-978-0-470-19242-9/86998-chapter-2-add_post-php-issue.html)

Master Yoda March 17th, 2012 10:13 AM

[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 [:I]
Is there any way to limit the size of the PHP box in this post?

Thanks!!

kenj March 17th, 2012 11:42 PM

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.

http://p2p.wrox.com/book-php-mysql-c...-properly.html

http://p2p.wrox.com/book-php-mysql-c...-view-php.html

http://p2p.wrox.com/book-php-mysql-c...e-55-56-a.html

http://p2p.wrox.com/book-php-mysql-c...hap-6-too.html

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

I hope this helps.

Master Yoda March 18th, 2012 06:10 AM

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 [:p]) 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!

Master Yoda March 18th, 2012 09:43 AM

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!! [:)]

Master Yoda March 20th, 2012 07:39 AM

[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.

klakier November 3rd, 2016 01:40 PM

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


All times are GMT -4. The time now is 12:38 AM.

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