1

嘿,我在我的 SQL/PHP/JAVA 应用程序中遇到了一个小问题我希望你们能提供帮助:) 我有一个 java 应用程序,当运行时连接到我的网站,当 java 应用程序验证它正在运行时,它会与我的网站对话我的网站为 java 应用程序和网站本身分配了一个会话 ID。

酷我们到目前为止好吗?

好吧,我的 java 应用程序定期将数据发送到名为 Dashboard.php 的页面我想做的是将数据保存到我的 Mysql 表中,然后当 Dashboard.php 从 sessionID 相同的 java 应用程序接收到新数据时我希望表格更新为刚刚收到的新数据

这是我到目前为止的 php,虽然它不起作用。

function update($script_name, $version, $runtime, $status, $ranged, $attack, $defense, $strength, $magic, $sessionID, $username)
{
    global $db;
    $sql = "SELECT * FROM Dashboard WHERE session_id = '$sessionID'";
    try {
        $results = $db->query($sql);
        if ($results->rowCount() <= 0) {
            $query = "INSERT INTO Dashboard (script_name, version, runtime, status, ranged, attack, defense, strength, magic, session_id, username) VALUES ('$script_name', '$version', '$runtime', '$status', '$ranged', '$attack', '$defense', '$strength', '$magic', '$sessionID', $username)";
            $db->exec($query);
        } else {
            foreach ($results as $row) {
                $timerunnew = $row['runtime'] + $runtime;
                $v4new = $row['ranged'] + $range;
                $v5new = $row['attack'] + $attack;
                $v6new = $row['defense'] + $defense;
                $v7new = $row['strength'] + $strength;
                $v8new = $row['magic'] + $magic;
            }
            $db->exec("UPDATE Dashboard SET `runtime` = $timerunnew, `ranged` = $v4new, `attack` = $v5new, `defense` = $v6new, `strength` = $v7new, `magic` = $v8new WHERE session_id = '$sessionID'");
        }
    } catch (PDOException $ex) {
        echo "fail";
    }
}

我也尝试过尝试ON DUPLICATE KEY UPDATE value = VALUES(value)但是我没有运气有人有解决方案吗?任何帮助将非常感激

4

1 回答 1

0

如果这是将记录插入Dashboard表中的唯一方法,那么两条记录就不可能共享相同的记录(除了and命令session_id之间发生的竞争风险)。在这种情况下,您应该:SELECTINSERT

  1. 确保在 上UNIQUE定义了一个键session_id

    ALTER TABLE Dashboard ADD UNIQUE KEY (session_id);
    
  2. 使用INSERT ... ON DUPLICATE KEY UPDATE,理想情况下与正确参数化的准备语句一起使用:

    $qry = $db->prepare('
      INSERT INTO Dashboard (
         script_name,  version,  runtime,  status,  ranged,  attack,
         defense,  strength,  magic,  session_id,  username
      ) VALUES (
        :script_name, :version, :runtime, :status, :ranged, :attack,
        :defense, :strength, :magic, :session_id, :username
      ) ON DUPLICATE KEY UPDATE
        runtime  = runtime  + VALUES(runtime),
        attack   = attack   + VALUES(status),
        defense  = defense  + VALUES(defense),
        strength = strength + VALUES(strength),
        magic    = magic    + VALUES(magic)
    ');
    
    $qry->execute([
      ':script_name' => $script_name,
      ':version'     => $version,
      ':runtime'     => $runtime,
      ':status'      => $status,
      ':ranged'      => $ranged,
      ':attack'      => $attack,
      ':$defense'    => $defense,
      ':strength'    => $strength,
      ':magic'       => $magic,
      ':session_id'  => $sessionID,
      ':username'    => $username
    ]);
    
于 2013-07-10T19:39:23.273 回答