Jump to content

How to check if database query is null?


shadrxninga

Recommended Posts

I'm trying to get a nickname system working for a little project, but I've run into a problem.

 

This code that I wrote here gets the users nickname from their username:

 

$user = $_GET['user'];
@mysql_select_db("db") or die( "Unable to select database");

$query = mysql_query("SELECT `nickname` FROM `info` WHERE `username`='$user'");

       WHILE($rows = mysql_fetch_array($query)):
           $nickname = $rows['nickname'];
           echo $nickname;
        endwhile;
?>

 

But the problem is, if the user doesn't have a nickname then it just turns up blank. How can I check if the output of $nickname is blank and if it is then just return their normal name ($user)

 

Thanks

 

Oh, and how to you format php code to look like php code on these forums?

Link to comment
https://forums.phpfreaks.com/topic/246948-how-to-check-if-database-query-is-null/
Share on other sites

use the [ php \] and [/ php \] tags without the ending backslashes.

 

For your query just use !empty

 

WHILE($rows = mysql_fetch_array($query)):
           $nickname = (!empty($rows['nickname'])) ? $rows['nickname'] : $rows['username']; // tells it to display username if nickname is empty
           echo $nickname;
        endwhile;

 

use the [ php \] and [/ php \] tags without the ending backslashes.

 

For your query just use !empty

 

WHILE($rows = mysql_fetch_array($query)):
           $nickname = (!empty($rows['nickname'])) ? $rows['nickname'] : $rows['username']; // tells it to display username if nickname is empty
           echo $nickname;
          endwhile;

 

There's only one problem with that. It may sound strange but... If the $nickname variable is blank - I want it to return the $user variable from the url.

That code will only return the username value in the database.

WHILE($rows = mysql_fetch_array($query)):
           $nickname = (!empty($rows['nickname'])) ? $rows['nickname'] : $user; // tells it to display username if nickname is empty
           echo $nickname;
          endwhile;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.