I figured it out. I had to add the user id from the MySQL table to the session cookie so it could be read with $_SESSION['user_id] outside of the database connection ($user_id). Here's the login page:
PHP Code:
<?php
session_start();
?>
<?php
if (isset($_SESSION['user'])) {
header("Location: view.php?id=$user_id"); }
?>
<?php
include 'dbc.php';
$user_name = mysql_real_escape_string($_POST['name']);
if ($_POST['Submit']=='Login')
{
$md5pass = md5($_POST['pwd']);
$sql = "SELECT id,user_name FROM users WHERE
user_name = '$user_name' AND
user_pwd = '$md5pass' AND user_activated='1'";
$result = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($result);
if ( $num != 0 ) {
// A matching row was found - the user is authenticated.
session_start();
list($user_id,$user_name) = mysql_fetch_row($result);
// this sets variables in the session
$_SESSION['user']= $user_name AND $_SESSION['user_id']= $id;
if (isset($_GET['ret']) && !empty($_GET['ret']))
{
header("Location: $_GET[ret]");
} else
{
header("Location: view.php?id=$user_id");
}
//echo "Logged in...";
exit();
}
header("Location: login.php?msg=ERROR: Incorrect username and password.");
//echo "Error:";
exit();
}
?>