我正在尝试循环一个对应于数据库中的播放器行的数组($ lineup_selected)。对于每个玩家,我想对数据库执行UPDATE查询,该查询将$ submissions_selected的值添加到total_picks列。我正在努力解决代码,因为它无法执行查询。请帮忙吗?!
// Select team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
// Loop through and update total_picks for each player in database present in lineup_selected array
$player_picks_query = "SELECT full_name, total_picks FROM table WHERE team=$team_selected";
$result = mysqli_query($conn, $player_picks_query);
while($row = mysqli_fetch_assoc($result)) {
$player = mysql_real_escape_string($row["full_name"]);
$add_player_picks = "UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name = '$player'";
}
答案 0 :(得分:1)
在您的选择请求中,您有一个显然是String的团队。所以,也许你可以尝试你的请求:"SELECT full_name, total_picks FROM table WHERE team='$team_selected'"
我不知道PHP是否足够聪明,可以使用引号。
答案 1 :(得分:1)
为什么不:
UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE team = '$team_selected'
这样,您只需要执行一个查询,并让数据库执行循环。否则,您首先要选择一些记录,然后让数据库更新每个记录以更新记录。
我认为全名是唯一的。如果没有,这意味着您的版本可以让更新查询每次都修改多条记录,因此我的方法无效
- 当我说明要消毒并将你的输入转义为保存(r)时,我似乎重复了很多评论。
编辑: 结合它应该来:
// set team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
$updatequery = "UPDATE table
SET total_picks = total_picks + ?
WHERE team= ?";
$stmt = mysqli_prepare($updatequery);
mysqli_stmt_bind_param($stmt, "is", $submissions_selected, $team_selected);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
我自己更喜欢pdo方法,但语法应该是这样的。
答案 2 :(得分:-1)
我认为如果只使用更新语句会更好。
首先,你内爆了你的数组
$lineup_selected = array("player1", "player2", "player3");
$players='".implode("','",$lineup_selected )."';
现在您可以更新表格
$updateStmt="UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name in (".$players.") and team=".$team_selected.";