跟踪用户的最新5次更新,PHP MySql

时间:2015-07-16 07:15:21

标签: php mysql

我正在尝试跟踪用户位置的最新6次更新。如果第7条记录到来,它将检查用户位置是否更新。如果更新,那么检查它是否低于6或更高然后6.如果大于6然后用第7个替换第一个,或者如果低于6然后插入为新记录。

我为它编写代码并且工作正常。但我如何优化我的代码? 或者这有任何错误的机会?

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "root";
    $dbname = "gpslocation";

    $user="testuser";
    $userLat="914";
    $userLng="111";
    $gpsTime="2015-07-16 12:00:36";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT * FROM gpslocations where userName='".$user."' and latitude='".$userLat."' and longitude = '".$userLng."'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
            //update location time here
            echo "User Location is all ready stored.";
        // output time of location
            $sql = "UPDATE gpslocations SET  gpsTime = '".$gpsTime."',lastUpdate=now() WHERE userName='".$user."' and latitude='".$userLat."' and longitude = '".$userLng."'";
                if ($conn->query($sql) === TRUE) {
                    echo "updated record time successfully";
                } else {
                    echo "Error in updated record time : " . $sql . "<br>" . $conn->error;
                }

    } else {

        //counting number of records of a user
        $countSql= "SELECT * FROM gpslocations where userName='".$user."' ";
        $countResult = $conn->query($countSql);
        //Dont want to store more then 6 record in DB
            if ($countResult->num_rows > 5) {           
            //update location  here
                echo "greater then 5";
                                //getting first location data
                    $sql = "SELECT * FROM gpslocations where userName='".$user."' ORDER BY lastUpdate  asc LIMIT 1;";
                    $result = $conn->query($sql);

                    if ($result->num_rows > 0) {
                        while($row = $result->fetch_assoc()) {
                            echo "id: " . $row["GPSLocationID"] ;
                            //updating data of first one row
                            $updateLastRecSql = "UPDATE gpslocations SET  lastUpdate=now(), gpsTime =  '".$gpsTime."',latitude='".$userLat."',longitude='".$userLng."' WHERE userName='".$user."' and GPSLocationID= '".$row["GPSLocationID"]."'";
                                if ($conn->query($updateLastRecSql) === TRUE) {
                                    echo "updated record time successfully";
                                } else {
                                    echo "Error in updated record time : " . $sql . "<br>" . $conn->error;
                                }
                        }
                    }

            } else {
                //insert data if not more then 6
                            $sql = "INSERT INTO gpslocations (userName, latitude, longitude,gpsTime)
                VALUES ('$user', '$userLat', '$userLng','$gpsTime')";

                if ($conn->query($sql) === TRUE) {
                    echo "New record created successfully";
                } else {
                    echo "Error: " . $sql . "<br>" . $conn->error;
                }
            }

    }
    $conn->close();
    ?>

1 个答案:

答案 0 :(得分:0)

如果我查看代码,您可以进行一些简单的更改以优化代码。例如,如果您需要知道行数,只需使用mysql COUNT功能。 https://dev.mysql.com/doc/refman/5.6/en/counting-rows.html

对于其余的,可以花4个查询来更新结果。如果使用INSERT ON DUPLICATE KEY查询,则可以将insert语句与update语句组合使用。

https://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html

为此,您需要userName, latitude, longitude上的unique_key。如果这样做,您可以将代码减少到下面的示例。重复键上的插入将在插入时返回1个受影响的行,在更新时返回2。

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "gpslocation";

$user="testuser";
$userLat="914";
$userLng="111";
$gpsTime="2015-07-16 12:00:36";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Insert or update record
$sql = "INSERT INTO gpslocations (username, latitude, longitude, gpsTime)
        VALUES ('{$user}', '{$userLat}', '{$userLng}', '{$gpsTime}')
        ON DUPLICATE KEY UPDATE gpsTime=values(gpsTime), lastUpdate=NOW()";
if ($conn->query($sql) === false) {
    echo "Error in updated record time : " . $sql . "<br>" . $conn->error;
} else {
    if ($conn->affected_rows === 1) {
        echo "New record created successfully";
    } else {
        echo "updated record time successfully";
    }
}

$sql = "DELETE FROM gpslocations WHERE GPSLocationID IN (
          SELECT GPSLocationID FROM (select GPSLocationID from gpslocations WHERE username='{$user}' order by lastUpdate DESC LIMIT 6,100) x
        )";
if ($conn->query($sql) === false) {
    echo "Error in deleting records: {$sql} <br> {$conn->error}";
} else {
    echo "{$conn->affected_rows} rows deleted.";
}

$conn->close();