在更新查询后获取行数据

Get row data after an Update query

我正在编写一个非常基础的 API 来管理现有唯一键的列表。当调用 getKey() 方法时,它要么 returns 已经分配的键,要么找到一个未使用的键并分配它。

在后者中,我必须在现有行上调用 UPDATE,将其标记为已分配。这样做之后,我再次查询相同的信息以获取行数据,我觉得这是相当多余的。虽然它有效,但我正在努力寻找自我改进的最佳实践,我希望在其中获得有关可能更好的实施的任何反馈。

<?php

require "Slim/Slim.php";
\Slim\Slim::registerAutoloader();

require "defines.php";

$GLOBALS['db'] = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);

// SLIM INSTANCE
$app = new \Slim\Slim();

$app->get('/getKey/:dlc/:serviceId', function ($dlc, $serviceId)
{
    $sql = "SELECT game_key FROM " . $dlc . " WHERE service_id = " . $serviceId . " LIMIT 1";

    if ($result = $GLOBALS['db']->query($sql))
    {
        // Check if we already have a GAME_KEY assigned
        if (mysqli_num_rows($result) >= 1)
        {
            echo "got an existing row!";
            $row = mysqli_fetch_assoc($result);
            echo $row["game_key"];
        }
        else
        {
            echo "no existing row, lets update one!";
            $sql = "UPDATE " . $dlc . " SET service_id = $serviceId WHERE service_id = 0 LIMIT 1";

            if ($GLOBALS['db']->query($sql))
            {
                $sql = "SELECT game_key FROM " . $dlc . " WHERE service_id = " . $serviceId;

                if ($result2 = $GLOBALS['db']->query($sql))
                {
                    $row = mysqli_fetch_assoc($result2);
                    echo $row["game_key"];
                }
            }
        }
    }
    else
    {
        echo "Query Failed!";
    }
});

// run the Slim app
$app->run();

?>

您最多可以使用 2 个语句:

// SELECT game_key matching $serviceId OR some with 0 if not found
$sql = "SELECT id, game_key, service_id FROM " . $dlc . " WHERE service_id = " . $serviceId . " OR service_id = 0 ORDER BY service_id DESC LIMIT 1";
if ($result = $GLOBALS['db']->query($sql))
{
    $row = mysqli_fetch_assoc($result);
    echo $row["game_key"];
    // Check if it is new key
    if($row["service_id"] == 0) {
        $keyId = $row["id"]
        $sql = "UPDATE $dlc SET service_id = $serviceId WHERE id= $keyId LIMIT 1";
        ... // continue to exec update query
    }
}

我假设您的 table

中有 "id" 主键列