tags:

views:

29

answers:

2

I was wondering how can I check if there is no tags entered into the database for a specific post if there are none, display no tags have been entered. How can I do this using PHP?

Here is my PHP & MySQL code.

$tag = array();
$dbc = mysqli_query($mysqli, "SELECT tags.tag
                  FROM posts_tags 
                  INNER JOIN tags ON tags.id = posts_tags.tag_id 
                  WHERE posts_tags.post_id = '" . $post_id . "' 
                  GROUP BY tags.tag");

if (!$dbc) {
    print mysqli_error($mysqli);
}  else {
    while($row = mysqli_fetch_array($dbc)){
    $tag[] = $row['tag'];
    }
}
+1  A: 

If the tag array is empty, then there are no tags:

if(empty($tag)){
   echo 'no tags have been entered';
}

You could also check for the number of rows returned:

if(mysqli_num_rows($dbc) == 0){
   echo 'no tags have been entered.';
}
Lekensteyn
this isn't working for some reason?
leftout
Did you query fail? Where did you put the codes?
Lekensteyn
it was a problem with my database I fixed it both answers work.
leftout
A: 

Use mysqli_num_rows and code like this:

$tag = array();
$dbc = mysqli_query($mysqli, "SELECT tags.tag
                  FROM posts_tags 
                  INNER JOIN tags ON tags.id = posts_tags.tag_id 
                  WHERE posts_tags.post_id = '" . $post_id . "' 
                  GROUP BY tags.tag");

if (!$dbc)
{
    print mysqli_error($mysqli);
}
elseif(!mysqli_num_rows($dbc))
{
    echo "no tags have been entered";
}
else
{
    while($row = mysqli_fetch_array($dbc))
    {
        $tag[] = $row['tag'];
    }
    print_r($tag);
}
shamittomar
this isn't working for some reason either?
leftout
Can you tell what error are you getting?
shamittomar
nothing is being displayed, I think there is something wrong on my side I'm looking now.
leftout
@leftout, code updated. Nothing is displayed because in the `while` block you did not use any `print`, `echo`, etc. Check new code now.
shamittomar
it was a problem with my database I fixed it both answers work.
leftout