gpt4 book ai didi

php - 如何在 sql 查询的一部分中将 2 个 foreach 循环正确组合在一起?

转载 作者:搜寻专家 更新时间:2023-10-31 21:20:01 24 4
gpt4 key购买 nike

我在数据库中有共享相同 FK 但唯一 PK 的信息,因此我将其循环显示在页面上。我想构建一个 SQL 更新查询来更新它。我现在有 2 个循环,但我不确定如何将它们完全组合以使其合二为一。

我遗漏了什么或我需要做什么才能获得我需要的结果,以便在我运行代码时更新应该更新的唯一字段?我是否应该在另一个 for-each 循环中放置一个 for-each 循环?这样可行吗?

这是连接数据库并从中获取信息的代码,然后是显示值和 id 字段的循环。

//connect
$sql_awards = "select `awards`, `awardsid` from inf_awards where inf_id = $vId";
$rs_awards = mysqli_query($vconncvnl, $sql_awards);

//display inputs
while ($rs_awards_rows = mysqli_fetch_assoc($rs_awards)) {
echo '<input type="text" name="awardact[]" id="awardact" class="awardactadd" value="' . $rs_awards_rows['awards'] . '">';
echo '<input type="hidden" name="txtaward[]" value="'. $rs_awards_rows['awardsid'] .'">';
}

所以现在我可以将信息获取到进程页面我还有一个 SQL 更新语句和一个循环

我用来显示奖项 ID 的 foreach 循环,然后是用于 sql 代码的 foreach 循环

//construction of loop for the awardsID field
$awardsId = '';
$award = $_POST['txtaward'];

foreach ($award as $awardid){
$awardsId .= $awardid;
}

//construction of the loop for building the SQL Update Query
$sql_up_award = '';
foreach ($vaccolates as $valuesawards) {
$sql_up_award .= sprintf("UPDATE inf_awards SET awards = %s WHERE inf_id = $vid AND awardsid = $awardsId ; ". "<br>", escapestring($vconncvnl, $valuesawards,'text'));
}

但是当我这样做时,它给了我

UPDATE inf_awards SET awards = 'john smith honorary' WHERE inf_id = 2 AND awardsid = 23; 
UPDATE inf_awards SET awards = 'Best scorer' WHERE inf_id = 2 AND awardsid = 23;

我猜这是上一个循环的原因,现在当我在其中调用它时,它只会循环满足要求的每个值,但此时只是“23”

我想要的结果是这样的

UPDATE inf_awards SET awards = 'john smith honorary' WHERE inf_id = 2 AND awardsid = 2; 
UPDATE inf_awards SET awards = 'Best scorer' WHERE inf_id = 2 AND awardid = 3;

最佳答案

嵌套循环不会解决它,因为您最终会得到 4 次更新。

您有两个数组,一个包含 ID,一个包含值。您可以制作一个 for 循环并通过索引获取匹配值。

但是,我认为这并不完全安全,因为我担心人们可能会将文本设为空,这样会搞砸你的数组,所以至少事先检查两个数组包含相同数量的项目是很重要的:

if (count($award) != count($valuesawards)) {

echo 'Please fill in all the names';

} else {

$sql_up_award = '';

//construction of the loop for building the SQL Update Query
$sql_up_award = '';

for ($i = 0; $i < count($award); $i++) (
$awardid = $award[$i];
$valuesawards = $vaccolates[$i];
$sql_up_award .= sprintf("UPDATE inf_awards SET awards = %s WHERE inf_id = $vid AND awardsid = $awardsId ; ". "<br>", escapestring($vconncvnl, $valuesawards,'text'));
}
}

关于php - 如何在 sql 查询的一部分中将 2 个 foreach 循环正确组合在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54745764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com