我在php while
循环中有以下代码,在这里你可以看到一个html select
标记。
如果selected
或$status = 1
,我想$status == 2
它的选项值。它的意思是Active
或Blocked
在此循环中,始终选择Blocked
选项$status == 2
但是我的mysql数据库中只有一个被阻止的数据。我在这里做错了什么?
PHP While Loop
$data = array();
$x = 1;
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $x;
$nestedData[] = $row["user_id"];
$nestedData[] = $row["address"];
$nestedData[] = $row["package_name"];
$status = $row['status'];
if( $status == 1) {
$statusMsg = "selected = 'selected'";
} elseif( $status == 2 ){
$statusMsg = "selected = 'selected'";
}
$nestedData[] = "
<select class='form-control' name='status' id='changeStatus'>
<option value=''>--Select--</option>
<option value='1' $statusMsg>Active</option>
<option value='2' $statusMsg>Blocked</option>
</select>";
$client_id = (int) $row['client_id'];
$nestedData[] = "<a class='btn btn-success btn-sm' href='{$site_url}toplevel/clients/update/$client_id'>Edit</a> <a href='#' data-toggle='modal' data-target='#myModal' class='btn btn-danger btn-sm' data-id='$client_id'>Delete</a>";
$data[] = $nestedData;
$x++;
}
答案 0 :(得分:1)
$statusMsg
是1还是2, selected = 'selected'
都将始终作为$row[status]
输出。
您需要添加另一个变量来区分这两个标记,并在循环开始时清除这两个变量。
$status = $row['status'];
$statusMsg1 = "";
$statusMsg2 = "";
if( $status == 1) {
$statusMsg1 = "selected = 'selected'";
} elseif( $status == 2 ){
$statusMsg2 = "selected = 'selected'";
}
$nestedData[] = "
<select class='form-control' name='status'>
<option value=''>--Select--</option>
<option value='1' $statusMsg1>Active</option>
<option value='2' $statusMsg2>Blocked</option>
</select>";