moorbes moorbes - 4 months ago 17
MySQL Question

Updating existing facebook user token

I made this code to first check if user exists based on userid, if yes it should update the existing row with token column, but unfortunately the code duplicates the user in a new row.

$userid = $user['id'];

$check="SELECT COUNT(*) FROM user WHERE userid = '$userid'";
$update="UPDATE user SET token='$accessToken' WHERE userid = '$userid'";
$rs1 = mysqli_query($db,$update);


$rs = mysqli_query($db,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {


echo "User exists, token updated<br/>";
}
else
{
$newUser="INSERT INTO user (userid, token) VALUES ('{$userid}', '{$accessToken}')";
if (mysqli_query($db,$newUser))
{
echo "User added.";
}
else
{
echo "Not working.<br/>";
}
}`


Could someone tell me where is the problem. Thanks!

Answer

Place the $update query inside the code block where you are sure that users is exists.

if($data[0] > 1) {
      $update="UPDATE user SET token='$accessToken' WHERE userid = '$userid'";
      $rs1 = mysqli_query($db,$update);

      echo "User exists, token updated<br/>";
}