2.7. Adding Posts

The next thing that needs to be provided for is a way for users to post new messages to the forums and have them saved in the database. This is the purpose of add_post.php. Again, it should only be made available to users who have logged in.

Two parameters may be passed in the URL when calling the script. Minimally, you should provide the id of the forum (fid). If the id of a parent message is also passed (mid) then it will be aggregated as a thread. Otherwise the parent message id will default to 0 marking the post as the start of a new thread.

include '401.php';

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

$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 forum id.</p>');
}
mysql_free_result($result);

The displayed form should collect the message information from ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.