Michael Philibin Michael Philibin - 1 year ago 32
PHP Question

if database entry null, do not display div

Have a database with option1, option2, option3, option4, option5 as columns. Options 1-3 have data entered, however, options 4-5 are NULL.

How can I set it so that a div is NOT displayed if option in database is NULL?

PHP CODE:

$sql = "SELECT option1, option2, option3, option4, option5 FROM options";
$result = mysqli_query($conn, $sql);
$null = NULL;

if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
if ($result != $null) {
echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option1"]. '</div2>' . '</div>';
}
else {
echo '<div class="null"></div>';
}
if ($result != $null) {
echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option2"]. '</div2>' . '</div>';
}
else {
echo '<div class="null"></div>';
}
if ($result != $null) {
echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option3"]. '</div2>' . '</div>';
}
else {
echo '<div class="null"></div>';
}
if ($result != $null) {
echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option4"]. '</div2>' . '</div>';
}
else {
echo '<div class="null"></div>';
}
if ($result != $null) {
echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option5"]. '</div2>' . '</div>';
}
else {
echo '<div class="null"></div>';
}
...


CSS CODE:

.null {
display: none;
}


At the moment, even for options 4-5, div class="null" is not working and div class="row" is being displayed (height=70px) but is blank.
Thanks.

Answer Source

You are comparing the actual query to null, not the individual columns.

$result = mysqli_query($conn, $sql);

The line above returns a mysqli-result object, not the rows or columns - use your $row variable in the loop, which holds each row, like this

if ($row['option1'] != null) {
    echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option1"]. '</div2>' . '</div>';
} else {
    echo '<div class="null"></div>';
}
if ($row['option2'] != null) {
    echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option2"]. '</div2>' . '</div>';
} else {
    echo '<div class="null"></div>';
}

See that this code compares $row['option1'] with null, instead of $result compared to null.

You can also just don't do anything if there are no rows, since you don't display the div at all.

if ($row['option1'] != null) {
    echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option1"]. '</div2>' . '</div>';
}
if ($row['option2'] != null) {
    echo '<div class="row">' . '<div1></div1>' . '<div2>' . $row["option2"]. '</div2>' . '</div>';
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download