Reputation: 1024
I have following code in php while
loop and here you can see a html select
tag.
I want to selected
it's option value if $status = 1
or $status == 2
. It's mean Active
or Blocked
In this loop it's always selected Blocked
option which Is $status == 2
But there are only 1 blocked data in my mysql database. What I am doing wrong here ?
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++;
}
Upvotes: 0
Views: 1309
Reputation: 4792
$statusMsg
will always be output as selected = 'selected'
on both tags regardless if the $row[status]
is 1 or 2.
You need to add another variable to distinguish between the two tags and clear both variables at the start of the loop.
$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>";
Upvotes: 1