因此,我有一个foreach循环,可在数据库中插入值,我想在循环结束时显示警报,并检查插入是否成功
我有这个
if (isset($_POST['alter'])) {
# code...
foreach ($_POST['id'] as $key => $id) {
$array1 = $_POST['name'][$key];
$array2 = $_POST['surname'][$key];
$array3 = $_POST['tel'][$key];
$array4 = $_POST['email'][$key];
$query = $link -> prepare("UPDATE table SET name = ? , surname = ? , tel = ? , email = ? WHERE id = ?;");
$query -> bind_param('sssss',$array1,$array2,$array3,$array4,$id);
$s = $query -> execute();
$query -> close();
if ($s==1){
?><div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>SUCCESS!</strong>
</div><?php
} else {
?><div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria- hidden="true">×</button>
<strong>ERROR.</strong>
</div><?php
}
}
}
但这将在页面中多次显示警报
我如何使其仅显示一个警报?
答案 0 :(得分:2)
要警告每个失败的更新,可以在循环中将值存储在数组中。然后,在循环结束时,如果该数组为空,则可以给出成功消息,否则将回显失败消息和失败数组的内容。
if (isset($_POST['alter'])) {
# code...
$failures = array();
foreach ($_POST['id'] as $key => $id) {
$array1 = $_POST['name'][$key];
$array2 = $_POST['surname'][$key];
$array3 = $_POST['tel'][$key];
$array4 = $_POST['email'][$key];
$query = $link -> prepare("UPDATE table SET name = ? , surname = ? , tel = ? , email = ? WHERE id = ?;");
$query -> bind_param('sssss',$array1,$array2,$array3,$array4,$id);
if (!$query -> execute()) {
$failures[] = "failed to update id $id with values ($array1, $array2, $array3, $array4)<br>";
}
$query -> close();
}
if (!count($failures)){
?><div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>SUCCESS!</strong>
</div><?php
} else {
?><div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria- hidden="true">×</button>
<strong>ERROR.</strong>
<?php
foreach ($failures as $failure) {
echo $failure;
}
?>
</div><?php
}
}
请注意,针对1
测试布尔值虽然可以在当前的PHP版本中运行,但这不是一个好习惯。您应该使用布尔值本身作为表达式,即使用if ($success)
,而不是if ($success == 1)
。