我正在编写一个管理现有唯一键列表的基本API。调用getKey()
方法时,它会返回已经分配的密钥,或者找到一个未使用的密钥并分配该密钥。
在后者期间,我必须在现有行上调用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();
?>
答案 0 :(得分:-1)
您可以使用最多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
}
}
我假设你的表中有“id”主键列