Search code examples
phpmysqlmysql-error-1064

insert into table or update for duplicate key error in php


I get Syntax error with my code in the query statement but I cannot figure out why. I have id, token, gpslat, gpslong as my table columns. I want to update record if token name is same otherwise insert. I am getting error. Following is my PHP code.

<?php

 header('Content-Type: application/json');

 $token = $_GET['token'];  
  $gps = $_GET['gps']; 
 $date = $_GET['gpslat'];
  $uname;

  $newlogin=FALSE; 
  $json;$idx;
  include("dbsave.php");

  $sql = "INSERT INTO whosonline (token,gpslat,gpslong) VALUES ('$token', '$date', '$gps') ON DUPLICATE KEY gpslat='$date',gpslong='$gps'";

  if ($conn->query($sql) === TRUE) {
  // echo "New record created successfully";
  $newlogin=TRUE;
  $idx= mysqli_insert_id($conn);

  $sql = "SELECT * FROM tokentable WHERE token='$token'";
  $result = $conn->query($sql);

   if ($result->num_rows > 0) {
    // output data of each row
     while($row = $result->fetch_assoc()) {
     $uname = $row["username"];
    }
    } else {
      $newlogin=FALSE;

        }


        } else {
    echo "Error: " . $sql . "<br>" . $conn->error;
      $newlogin=FALSE;
      }

Error I am getting : Error: INSERT INTO whosonline (token,gpslat,gpslong) VALUES ('{3CAD0B79-41DA-2CFC-9A9A-644B3E1A93C7}', '11.1241', '101.21020') ON DUPLICATE KEY gpslat='11.1241',gpslong='101.21020'<br>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'gpslat='11.1241',gpslong='101.21020'' at line 1{"status":0,"msg":{"msg":"Error adding user!"}}


Solution

  • You forgot the UPDATE keyword in the ON DUPLICATE KEY portion of the query:

    $sql = "INSERT INTO whosonline (token,gpslat,gpslong) VALUES ('$token', 
           '$date', '$gps') ON DUPLICATE KEY UPDATE gpslat='$date',gpslong='$gps'";