我正在为大学作业制作一个基本的民意调查脚本,但我无法更新单行SQL。相反,所有行都是更新。
所以这里我们得到了脚本的第一部分,它从所选的轮询ID中提取所有相关记录。让我们调用这个脚本 show.php
<?php
$pid = (int)$_GET['pid'];
$query = "
SELECT
Player_ID,
Player_Name
FROM players WHERE Team_ID = :pid
";
$query_params = array(
':pid' => $pid,
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
?>
<div class="container contain well">
<h3>Please select player</h3>
<form action="vote.php" method="post">
<input type="hidden" name="pid" value="<?php echo $_GET['pid']; ?>" />
<?php foreach($rows as $row): ?>
<input type="radio" name="player" value="<?php echo $row['Player_ID']; ?>" id="<?php echo $row['Player_ID']; ?>"><label for="<?php echo $row['Player_ID']; ?>"><?php echo $row['Player_Name']; ?></label><br>
<?php endforeach; ?>
<input type="submit" value="Vote »" class="btn btn-primary" />
</form>
</div>
现在用户选择他希望投票给哪个玩家的脚本发送一个POST请求让我们说 vote.php
<?php
require("database.obj.php");
$pid = (int)$_POST['pid'];
$query = "
UPDATE players
SET
Player_Votes = Player_Votes+1;
WHERE
( Player_ID = :player )
";
$query_params = array(
':player' => $_POST['player']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
header("Location: results.php?pid=$pid");
die("Redirecting to results.php?pid=$pid");
最后是 results.php 页面,其中显示了结果
$pid = (int)$_GET['pid'];
$query = "
SELECT
Player_ID,
Player_Name,
Player_Votes
FROM players WHERE Team_ID = :pid
";
$query_params = array(
':pid' => $pid,
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
?>
<div class="container contain well">
<h3>Player results</h3>
<?php foreach($rows as $row): ?>
<p><?php echo $row['Player_Name']; ?>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="<?php echo $row['Player_Votes']; ?>" aria-valuemin="0" aria-valuemax="100" style="width:<?php echo $row['Player_Votes']; ?>%;">
<?php echo $row['Player_Votes']; ?> Votes
</div>
</div>
<?php endforeach; ?>
</div>
问题在于show.php或vote.php(vote.php处理UPDATE查询)但是我不知道问题出在哪里。正如我所说的那样,数据被插入到Players_Votes中,但它插入了所有与玩家相关的玩家,比如说Team_ID = 1
有人可以帮助我吗?提前谢谢。
答案 0 :(得分:0)
在;
子句之前的更新语句中有分号(where
)。这会将您的语句分成两个语句 - 一个update
没有where
子句,它会更新所有记录(如您所述),以及一个以where
开头的语句它不是有效的SQL。
要解决此问题,您应该删除该分号:
$query = "
UPDATE players
SET
Player_Votes = Player_Votes+1 -- Semicolon removed here
WHERE
( Player_ID = :player )
";