I'm a bit of a noob- and I'm having a hard time...
I need a bit of of code that searches a db table to find the row that matches the $id variable. There's a field in that table 'description' that I need to grab. If it's null, I need to show one message, if not another. Here's the code I have (I know I need to add the mysqli escape string, just doing this real quick from memory):
$query = "SELECT description FROM posts WHERE id = $id";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC) ;
if(!$row){
echo "<p>'No description'</p>";
} else {
echo '<p>' . $row['description'] . '</p>';
}
mysqli_fetch_array
will fetch a row regardless of if the columns in that row are null. You want to be checking if $row['description']
is set instead of if $row
is set:
$query = "SELECT description FROM posts WHERE id = $id";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(isset($row['description'])) {
echo "<p>No description</p>";
} else {
echo '<p>' . $row['description'] . '</p>';
}
EDIT: Or, as an alternative, you can not fetch rows from the database where description is NULL:
$query = "SELECT description FROM posts WHERE id = $id AND description IS NOT NULL LIMIT 1";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(! $row) {
echo "<p>No description</p>";
} else {
echo '<p>' . $row['description'] . '</p>';
}
Now you'd check to see if you were able to grab a row or not.
The !$row
will only occur if no record is found. If the field description is really null
, you have to check it this way:
if(is_null($row['description'])){
but I recommend you to check if the value is empty (or 0 or null):
if(empty($row['description'])){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With