Page 1 of 1

Saving User Login information

Posted: Fri Jan 17, 2014 3:26 am
by SalientAnimal
Hi All,

as part of my login function I am storing any failed login attempts in one table, but also to ensure that users are using the system I am storing successful login attempts in a different table. To prevent a this table from getting too big I only want to store one record per user and thus update their last login date when they login again.

I have tried using the following code, but nothing is being written to my table on a successful login. I can only assume that my script is copletely wrong as I am really still learning how to all the functions etc work.

Here is my code:

Code: Select all

                    $mysqli->query("SELECT * FROM login_success WHERE user_id = '$user_id'");
					if			  (mysql_num_rows($mysqli) > 0)
						{
						$mysqli->query("UPDATE login_success SET time = NOW() WHERE user_id = '$user_id'");
						}
					else
						{
						$mysqli->query("INSERT INTO login_success(user_id, time) VALUES ('$user_id', now()");
						}
					//UPDATE login_success SET time = now() where user_id = '$user_id'");							  
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    //$now = time();
                    $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', now())");
                    return false;

Re: Saving User Login information

Posted: Fri Jan 17, 2014 1:35 pm
by social_experiment

Code: Select all

<?php
 "SELECT * FROM login_success WHERE user_id = '$user_id'"
?>
^ this line is not a very good way to check for presence of something (ask yourself why do you have to select * to count a single row?) ; rather use something like

Code: Select all

<?php
 $sql = $mysqli->query("SELECT COUNT(`id`) FROM login_success WHERE user_id = '$user_id'");
 // where id is your table's primary, auto-incrementing key
 $result = mysqli_fetch_array($sql);
 $rows = $result[0];

 if ($rows == 1) {
    // update, whatever
 }
?>
Are you mysqli_ functions? If so, mysql_num_rows() won't work because it's not a mysqli_ function.

Re: Saving User Login information

Posted: Sat Jan 18, 2014 10:13 am
by Celauran
Why even use a separate login_success table instead of a column in your user table? Also, what about login attempts where the username is (also) incorrect? Logging time but not IP?