Reputation: 175
I have a table which contains some Role_codes Find below table
I'm able to get all distinct role_code from the table but in the case NULL the result is blank.
Below code for the same:
<?php
if ($role_code === 'BOB')
{
$sql = "SELECT distinct role_code FROM `create_user`";
$result = $pdoConn->query($sql);
if ($result !== false)
{
echo "<div class='w3-container w3-responsive w3-round w3-padding-
large' style='width:95%;margin:10px;'>";
echo " <h4 class='w3-text-indigo'>Admin please select role to view
record.</h4>
<select id='view_record' name='view_record' class='w3-input w3-light-grey' style='width:90%'><option value='select Role'>Select Role</option>";
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$role_id = $row["role_code"];
echo "<option value=$role_id>" . $row["role_code"] . "</option>";
}
echo "</select></div>";
}
}
the above code is returning all the unique values but in the case Null it is returning blank.
Upvotes: 0
Views: 1412
Reputation: 708
I think you need to check for NULL
value :
if($variable === NULL) {...}
NOT
if($variable === 'NULL') {...}
Because NULL
is not a string if you check NULL value as like other string value like NULL
then the condition will not check for NULL
value.
Upvotes: 0
Reputation: 4820
There's no concept of null in HTML content. When you echo
null
in PHP, you get an empty string. I would suggest changing your while statement to this:
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$role_id = $row["role_id"];
echo "<option value='" . (is_null($role_id) ? "null" . $role_id) . "'>" . $row["role_id"] . "</option>";
}
...which then sets the value of the option
to the string "null"
. Then, when receiving the data back on server-side after a form submission, you can convert back to null
like this:
$role_id = ($_POST['view_record'] === 'null' ? null : (int)$_POST['view_record']);
Doing it this way means you preserve not only null
values back and forth, but you also cater for role_id
= 0
, and are converting the client data from string (which is what all HTML posted variables are) to the correct database type.
Upvotes: 1
Reputation: 95
Use this in ur code
if(is_null($result['role_code']))
{
echo "<option value='0'>Null</option>";
}else{
echo "<option value='1'>Result...</option>";
}
and see
How to check if mysql returns null/empty
and
PHP Check for NULL
Upvotes: 1