I have been going in circles all day trying to get this to work.

I have a login script that I want to be able to update the database with the last time a user logs in. The problem is it won't UPDATE the database.

I have tried quite a few ways but no luck.

The user logs in with an email address and a password.

I assume I need to use something along these lines:

// if $email is defined update the old entry
   if( $email )
   {
      $query = "UPDATE `users` SET `entry`= NOW() WHERE `email`='$email'";
   }

But I'm not sure where to put it being that I'm using Sessions and 2 login pages (login.php and loggedin.php").

Am I going about this the wrong way? or is there something easier and maybe more safe?

Here are my 2 pages:

login.php

<?php # Script 1.3 login.php

// Send Nothing to the browser prior to the setcookie() lines!

// Check if the form has been submitted.
if (isset($_POST['submitted'])) {

include ("db.inc.php"); // Connect to db.
$errors = array(); //Initialize error array.

// Check for an email address.
if (empty($_POST['email'])) {
	$errors[] = 'You forgot to enter your email address.';
} else {
	$e = mysql_real_escape_string($_POST['email']);
}

//Check for a password.
if (empty($_POST['password'])) {
	$errors[] = 'You forgot to enter your password.';
} else {
	$p = mysql_real_escape_string($_POST['password']);
}

if (empty($errors)) { //If everything's OK.

//Retrieve the user_id and first_name for that email/password combination.
$query = "SELECT user_id, first_name, last_name, email FROM users WHERE email='$e' AND password=SHA('$p')";
$result = @mysql_query ($query); //Run the query.
$row = mysql_fetch_array ($result, MYSQL_NUM); //Return a record, if applicable.

if ($row) { // A record was pulled from the database.

//Set the session data & redirect.
session_name ('VisitID');
session_set_cookie_params (7200, '/', '');
session_start();
$_SESSION['user_id'] = $row[0];
$_SESSION['first_name'] = $row[1];
$_SESSION['last_name'] = $row[2];
$_SESSION['email'] = $row[3];

//Redirect the user to the loggedin.php page.
//Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
//Check for a trailing slash.
if((substr($url, -1) == '/') OR (substr($url, -1) == '||') ) {
	$url = substr ($url, 0, -1); //Chop off the slash.

}
//Add the page.
$url .= '/loggedin.php' . SID; //Add the session name & ID.

header("Location: $url");
exit(); //Quit the script.

} else { //No record matched the query.
$errors[] = 'The email address and password entered do not match those on file.'; //Public message.
$errors[] = mysql_error() . 'Query: ' . $query; //Debugging message.
}

} //End if (empty($errors)) IF.

mysql_close(); //Close the databse connection.

} else { //Form has not been submitted.
$errors = NULL;
}

//End of the main Submit conditional.

//Begin the page now.
$page_title = 'Login';
include ('header.php');

if (!empty($errors)) { //Print any error messages.
echo '<table class="mytable2" width="800" align="center"><tr><td>';
echo '<h1 id="mainhead">Error!</h1>
<p class="error">The following error(s) have occured:<br>';
foreach ($errors as $msg) { //Print each error.
echo " - $msg<br>\n";
}

echo '</p><p>Please try again!</p>';
echo '</td></tr></table>';
}

//Create the form

?>

<table class="mytable2" width="800" align="center">
<tr><td width="50">
</td><td width="750">

<br>

<h2>Registered Users Login</h2>
<form action="login.php" method="post">
	<p>Email Address: <input type="text" name="email" size="30" maxlength="40"></p>
	<p>Password: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="password" size="20" maxlength="40"></p>
	<p><input type="submit" name="submit" value="Login"></p>
	<input type="hidden" name="submitted" value="TRUE">
	</form>

<br><a href="forgot_password.php">Forgot Password?</a><br><br>

<table class="mytable2" width="600" align="center">
<tr><td>
<br><center><h3><font color="900000">Not registered yet?</font>&nbsp;&nbsp;&nbsp;&nbsp; <a href="updates.php">Please Register</a></h3></center>
<center>You must be a registered user to recieve updates, special offers<br> and to be able to access member only areas.</center><br><br>
<center><a href="updates.php">Why register?</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="updates.php">Privacy Policy</a></center><br>
</td></tr></table>
<br>
</td></tr></table>
	<?php include ('footer.php'); ?>

<b>And the other:</b>

loggedin.php

<?php # Script 1.0 loggedin.php
# User is redirected here from login.php

session_name ('VisitID');
session_set_cookie_params (7200, '/', '');
session_start(); //Start the session.

//If no session value is present, redirect the user.
	if (!isset($_SESSION['user_id'])){

	//Start defining the URL.
	$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
	//Check for a trailing slash.
	if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
		$url = substr ($url, 0, -1); //Chop off the slash.

	}
	$url .= '/index.php'; //Add the page.
	header("Location: $url");
	exit(); //Quit the script.
}

//Set the page title and include the header.
$page_title = 'Logged In!';
include ('index.php');

//Print a customized message.

echo '<table class="mytable2" width="800" align="center"><tr><td width="50"></td><td width="750">';
echo "<h1>Logged In!</h1><p>You are now logged in, {$_SESSION ['first_name']}!</p><p><br><br></p>";
echo '</td></tr></table>';



include ('footer.php'); 

?>

    It seems to me that I need to code the loggedin.php page to pickup the info for the database being this is where the info is transferred to.

    This looks like it should work but it doesn't, I check the database field 'entry' and it still says '0000-00-00 00:00:00'.

    What am I missing?

    loggedin.php

    <?php # Script 1.0 loggedin.php
    # User is redirected here from login.php
    
    session_name ('VisitID');
    session_set_cookie_params (7200, '/', '');
    session_start(); //Start the session.
    
    //If no session value is present, redirect the user.
    	if (!isset($_SESSION['user_id'])){
    
    	//Start defining the URL.
    	$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
    	//Check for a trailing slash.
    	if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
    		$url = substr ($url, 0, -1); //Chop off the slash.
    
    	}
    	$url .= '/index.php'; //Add the page.
    	header("Location: $url");
    	exit(); //Quit the script.
    }
    
    //Set the page title and include the header.
    $page_title = 'Logged In!';
    include ('index.php');
    
    //Print a customized message.
    
    echo '<table class="mytable2" width="800" align="center"><tr><td width="50"></td><td width="750">';
    echo "<h1>Logged In!</h1><p>You are now logged in, {$_SESSION ['first_name']}!</p><p><br><br></p>";
    echo '</td></tr></table>';
    
    
    //Database Connection
       include $_SERVER['DOCUMENT_ROOT'] . '/db.inc.php';
    
       // get the variables from the URL request string
       $user_id = $_REQUEST['user_id'];
       $first_name = $_REQUEST['first_name'];
       $last_name = $_REQUEST['last_name'];
       $ordered = $_REQUEST['ordered'];
       $email = $_REQUEST['email'];
       $entry = $_REQUEST['entry'];
    
    // if $user_id is defined, update the old entry
       if( $user_id )
       {
          $query = "UPDATE `users` SET `first_name`='$first_name',`last_name`='$last_name', `email`='$email', `entry`='$entry' WHERE `user_id`='$user_id'";
       }
    
       // save the info to the database
       $results = mysql_query( $query );
    
    
    include ('footer.php'); 
    
    ?>

    See previous post for the login.php.

      I realized that I don't need the loggedin.php page, so I just redirected the login.php to the index.php and check the SESSIONS to see what needs to be displayed.

      But I still can't get the database to update the last time a user logged in.

      I created a new field in the db named 'entry' and set it 'DATETIME', seems like the following should work, but it doesn't, can anyone help?

      // if $user_id is defined, update the entry
         if( $user_id )
         {
            $query = "UPDATE `users` SET `first_name`='$first_name',`last_name`='$last_name', `email`='$email',  `entry`='$entry' WHERE `user_id`='$user_id'";
         }

      But the database still shows - 0000-00-00 00:00:00

      I'm not real well versed on SESSIONS, but this appears to be where the problem lies?

      I'm having some issues with 404 errors using the SESSIONS, if you can take a look at the site and see what might be wrong - http://www.ShopJNK.com

        Well I had to do this one on my own.

        I added :

        $query = "UPDATE `users` SET `entry`= NOW() WHERE `user_id`='$user_id'";
        
           $results = mysql_query( $query );

        near the end of the myaccount.php page, this way when a user logged into his/her account it would record the DATETIME in the database.

        I knew it had to be something simple, just needed to take a step back and look.

          I like that you did it on your own (I could have helped first time seeing your post :-) You may not have gotten a response where you posted so much code initially. Sometimes responders see that and go..."whoa, I have better things to do than read through all of that!" Be sure to mark your thread RESOLVED

            bretticus wrote:

            I like that you did it on your own (I could have helped first time seeing your post :-) You may not have gotten a response where you posted so much code initially. Sometimes responders see that and go..."whoa, I have better things to do than read through all of that!" Be sure to mark your thread RESOLVED

            Hi bretticus - I'm not complaining, I have had great success at this board, and i am very thankful for all the help that is here.

            I was more celebrating that I figured it out. I am not interested in having others do my coding but sometimes its good to have fresh eyes to see what is missing.

            As for all of the code being posted - Sometimes its easier to see a little more to understand what is trying to be accomplished, maybe I will try to limit next time I post, because you're right its hard to wade through long scripts.

            Anyway thanks for replying, I do appreciate the forums.

              And sorry if you thought I was implying that you were complaining. I didn't mean to do that. I just thought it was refreshing somebody solved his or her own problem. That really bumps up the respect for that person for me because it shows they are serious about the trade.

              As for the comment on lots of code, I just thought I was being helpful (obviously, I was not.) 🙂

                Write a Reply...