所以当我删除表格中的条目时,我想要更新每个列oneToFive
(这是一个从1到5的数字):
所以我的表看起来像这样
|oneToFive|name|
----------------
|1 |a |
|2 |b |
|3 |c |
|4 |d |
|5 |e |
假设我删除了名称为d的行,那么表格将如下所示:
|oneToFive|name|
----------------
|1 |a |
|2 |b |
|3 |c |
|5 |e |
我希望它看起来像:
|oneToFive|name|
----------------
|1 |a |
|2 |b |
|3 |c |
|4 |e |
该表也可能不完整,例如它可能是:
|oneToFive|name|
----------------
|1 |a |
|2 |b |
|3 |c |
如果我删除了一个,我会想要它:
|oneToFive|name|
----------------
|1 |b |
|2 |c |
所以我尝试了这个疯狂的代码,我写了所有更新查询,然后执行删除行后存在的更新查询。但这不起作用。
//find query
if($result === 5){
}else if($result === 4){
$query2 = "UPDATE faveMonth
SET oneToFive='4'
WHERE oneToFive='5'";
}else if($result === 3){
$query3 = "UPDATE faveMonth
SET oneToFive='3'
WHERE oneToFive='4'";
$query2 = "UPDATE faveMonth
SET oneToFive='4'
WHERE oneToFive='5'";
}else if($result === 2){
$query4 ="UPDATE faveMonth
SET oneToFive='2'
WHERE oneToFive='3'";
$query3 = "UPDATE faveMonth
SET oneToFive='3'
WHERE oneToFive='4'";
$query2 = "UPDATE faveMonth
SET oneToFive='4'
WHERE oneToFive='5'";
}else {
$query5 ="UPDATE faveMonth
SET oneToFive='1'
WHERE oneToFive='2'";
$query4 ="UPDATE faveMonth
SET oneToFive='2'
WHERE oneToFive='3'";
$query3 = "UPDATE faveMonth
SET oneToFive='3'
WHERE oneToFive='4'";
$query2 = "UPDATE faveMonth
SET oneToFive='4'
WHERE oneToFive='5'";
}
//run querys
if($result === 5){
}else if($result === 4){
if(mysqli_query ($con,$query2))
{
}
else
{
die("error updating other row(s)");
}
}else if($result === 3){
if(mysqli_query ($con,$query2))
{
}
else
{
die("error updating other row(s)");
}
if(mysqli_query ($con,$query3))
{
}
else
{
die("error updating other row(s)");
}
}else if($result === 2){
if(mysqli_query ($con,$query2))
{
}
else
{
die("error updating other row(s)");
}
if(mysqli_query ($con,$query3))
{
}
else
{
die("error updating other row(s)");
}
if(mysqli_query ($con,$query4))
{
}
else
{
die("error updating other row(s)");
}
}else {
if(mysqli_query ($con,$query2))
{
}
else
{
die("error updating other row(s)");
}
if(mysqli_query ($con,$query3))
{
}
else
{
die("error updating other row(s)");
}
if(mysqli_query ($con,$query4))
{
}
else
{
die("error updating other row(s)");
}
if(mysqli_query ($con,$query5))
{
}
else
{
die("error updating other row(s)");
}
}
你能想到更好的方法吗?
答案 0 :(得分:2)
你可以使用像这样的单一陈述
UPDATE faveMonth SET oneToFive = oneToFive - 1 WHERE oneToFive > x
删除oneToFive == x
答案 1 :(得分:0)
您可以使用循环而不是使用if else
链。
示例:
$result = ... // result from query
$count = ... // number of results in query
for ($i = 1; $i++; $i < $count)
{
// update $result[$i]'s oneToFive with $i
}
这不是一个完整的实现,只是一个想法。
效率不高,您应该使用kingkero
的解决方案。