-7

I would like to know the use/meaning of ! in if(!$db). If it were to be if($db) (without the exclamation mark), I'll understand.

I've tried searching Google and PHP.net for it but got nothing. Please can someone help me?

Here's the code:

if(!$db)

die("Database not configured.");

if(!mysql_select_db("$dbname",$db))

die("No database selected.");
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Inyavic
  • 11
  • 3
  • You need to edit your question and show the code you're talking about. – Benny Hill Feb 14 '14 at 03:31
  • The expression `!$var` can be thought of as `$var == false`. – Ja͢ck Feb 14 '14 at 03:45
  • See also: [logical operators](http://php.net/manual/en/language.operators.logical.php). – Ja͢ck Feb 14 '14 at 03:47
  • Simply said and in layman's terms: It reads as "**if** there is `no` database connection established, stop the process and show the error message `Database not configured.`". Then it reads as "**if** there is `no` database selected, then show the error message `No database selected.`" - The `no` part is the `!` exclamation mark. `die()` means `stop` the process. – Funk Forty Niner Feb 14 '14 at 03:51
  • And this `if(!mysql_select_db("$dbname",$db))` should not have any quotes in it. Therefore it should read as `if(!mysql_select_db($dbname,$db))` – Funk Forty Niner Feb 14 '14 at 03:56

2 Answers2

1

The ! sign negates an expression. Without seeing any of the actual code, we can only guess what your program does. I suspect that the code you are looking at tries to open a connection to a database. If the connection fails, the expression !$db will be true ($db would evaluate to false). This probably prompts the code to handle the exceptions and print and error statement etc.

hanno
  • 6,401
  • 8
  • 48
  • 80
0

The behaviour of that operator is described here in the manual.

It yields TRUE if the expression was not TRUE and vice-versa.

In this particular case you could achieve the same thing as:

mysql_connect( ... ) or die("Database not configured.");
mysql_select_db("$dbname",$db) or die("No database selected.");

Btw, you shouldn't use mysql_ functions anymore; consider switching to either mysqli or PDO.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • I'm not sure what you're asking me. – Ja͢ck Feb 14 '14 at 03:58
  • @Fred, the db contains the dbname and dbuser – Inyavic Feb 14 '14 at 04:02
  • *"I would like to know the use/meaning of ! in if(!$db). If it were to be if($db) (without the exclamation mark), I'll understand."* - [`Your question has been answered`](http://stackoverflow.com/questions/21770302/use-of-in-ifdb#comment32934748_21770302) – @Inyavic – Funk Forty Niner Feb 14 '14 at 04:03