Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & MySql check if table is empty

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>';
}
like image 698
user517593 Avatar asked Jan 31 '11 17:01

user517593


2 Answers

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.

like image 58
Josh Avatar answered Oct 16 '22 07:10

Josh


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'])){
like image 22
Marc Avatar answered Oct 16 '22 08:10

Marc