如何在循环中选择php中的html选项值?

时间:2017-01-14 06:29:03

标签: php

我在php while循环中有以下代码,在这里你可以看到一个html select标记。

如果selected$status = 1,我想$status == 2它的选项值。它的意思是ActiveBlocked

在此循环中,始终选择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>&nbsp;<a href='#' data-toggle='modal' data-target='#myModal' class='btn btn-danger btn-sm'  data-id='$client_id'>Delete</a>";

    $data[] = $nestedData;

    $x++;
}

1 个答案:

答案 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>";