I ran into a problem, so when user attempts to login and it fails (wrong username & password entered) the data needs to be saved in database but it just won't work. 
If i put INSERT INTO in `if ($pw == $row['passwd']` it will work but I want to write it on else like in example.

```
    <?php
session_start();
require('connect.php');

$mail = $_POST['mail'];
$pw = $_POST['password'];

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $lastip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $lastip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $lastip = $_SERVER['REMOTE_ADDR'];
}

$time = date('Y-m-d H:i:s');

$query = "SELECT * FROM `users` WHERE `login_email`='$mail' AND `passwd`='$pw'";
$result = mysql_query($query);
if(!$result){$_SESSION['error'] = 1;Header("Location: login.php");}
while ($row = mysql_fetch_assoc($result)) {
    if ($pw == $row['passwd'])
    {
    $_SESSION['logiran'] = 1;
    $_SESSION['mail'] = $mail;
    $_SESSION['error'] = 0;
    $_SESSION['sucess'] = 1;
    $_SESSION['msg'] = 0;
    $_SESSION['subuser'] = 0;
    $_SESSION['subcid'] = $row['id'];
    $query = "UPDATE `users` SET `login` = '$time' WHERE `login_email`='$mail' AND `passwd`='$pw'";
    mysql_query($query);
    $query = "UPDATE `users` SET `last_ip` = '$lastip' WHERE `login_email`='$mail' AND `passwd`='$pw'";
    mysql_query($query);
    Header("Location: index.php");
    }
    else
    {
    $query = "INSERT INTO `alerts`(`ipaddress`, `user`, `added`) VALUES ('$lastip', '$mail', '$time')";
    mysql_query($query);
    $_SESSION['error'] = 1;
    $_SESSION['logiran'] = 0;
    $_SESSION['subcid']  = 0;
    $_SESSION['subuser'] = 0;
    Header("Location: login.php");
    }
}

?>

```