我在查询语句中的代码出现语法错误,但我不知道为什么。我将id, token, gpslat, gpslong作为表列。如果令牌名称相同,我想更新记录,否则插入。我出错了。以下是我的PHP代码。

<?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: 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!"}}

最佳答案

您在查询的UPDATE部分中忘记了ON DUPLICATE KEY关键字:

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

09-20 01:25