1

I have a database and i am trying to make login times count using php this is my code :

$GetLoginTimes = "Select Login_Times from usertable where email = '$email'";
$GetLoginTimes2 = mysqli_fetch_array($GetLoginTimes);
$LoginTimesEdited = $GetLoginTimes2 + 1;
$UpdateLastLogin = "UPDATE usertable SET Login_Times = '$LoginTimesEdited' WHERE email = '$email'";
mysqli_query($con, $UpdateLastLogin);

when i login the login_times is set to 1 but when i do it again it stays the same TIA!

2 Answers2

2

You don't need to retrieve the login count before updating it, update it in one request like that :

$UpdateLastLogin = "UPDATE usertable SET login_times = login_times + 1 where email  = '$email'";
mysqli_query($con, $UpdateLastLogin);
Yoleth
  • 1,269
  • 7
  • 15
1

the problem in your code is you didn't use $result in the right way, where is mysqli_query()?

$GetLoginTimes = "Select Login_Times from usertable where email = '$email'";
$GetLoginTimes2 = mysqli_fetch_array($GetLoginTimes);

it should be like this:

$GetLoginTimes = "Select Login_Times from usertable where email = '$email'";
$result = mysqli_query($con, $GetLoginTimes);
$GetLoginTimes2 = mysqli_fetch_array($result);

and the second problem is when you retrieve the row, you didn't separate the Login_Times column from the row with $LoginTimesEdited[0], so this code:

$LoginTimesEdited = $GetLoginTimes2 + 1;
$UpdateLastLogin = "UPDATE usertable SET Login_Times = '$LoginTimesEdited' WHERE email = '$email'";
mysqli_query($con, $UpdateLastLogin);

should be like this:

$LoginTimesEdited = $GetLoginTimes2 + 1;
$first_element = $LoginTimesEdited[0];
$UpdateLastLogin = "UPDATE usertable SET Login_Times = '$first_element' WHERE email = '$email'";
mysqli_query($con, $UpdateLastLogin);

to prevent SQL injection you should use the prepare statement here is your example with prepare statement:

$email = "example@example.com";
$stmt = $conn->prepare("UPDATE usertable SET Login_Times= Login_Times + 1 where email=?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->close();
$conn->close();

read this article to learn how to work with mysql

https://www.w3schools.com/php/php_mysql_select.asp

Raskul
  • 1,674
  • 10
  • 26