• Displaying certain text when MySQL table is empty
    4 replies, posted
Hey, I'm quite new to MySQL, and I was wondering: How do I display a certain text, like "The table is empty" if a table is empty, and the contents of the table if there is something in it? Say, I've got a database named whatever, and in that database I have a table called 'Names' and there is one field, called 'name', and I want it to display the names in that table, but I want it to say "There are no names to show." if there are no names in the table. How would I go about doing this?
[php] $sql = mysql_query("SELECT name FROM Names") or die(mysql_error()); if(mysql_num_rows($sql) > 0){ while($row = mysql_fetch_array($sql)){ $name = $row['name']; echo $name; } } else { echo "There are no names to show"; } [/php] I edited it a bit.
Trying that now. [editline]05:04PM[/editline] Ok, maybe I'm acting really stupid; it displays the text I want it to say when it's empty, but it doesn't display the text when there's something in it. I'm doing this: [php] <?php mysql_connect("host", "username", "password"); mysql_select_db("database"); $res = mysql_query("SELECT name FROM names"); if(mysql_num_rows($res) > 0){ while ($obj = mysql_fetch_object($res)) { echo $obj->name."<br><hr>"; } } else{ echo 'There are no names to be displayed.'; } ?> [/php] What am I doing wrong? [editline]05:06PM[/editline] Also, maybe I should've added the "OR die(mysql_error())" part, although I don't think that it's related to the problem.
Oh, -snip-.
So, any thoughts? Wait, I missed his edit. [editline]05:49PM[/editline] Oh no, I've been incredibly stupid, I just made an error in the php to add the names to the list, that's why it wasn't displaying anything, still, thanks for your help :)
Sorry, you need to Log In to post a reply to this thread.