0

I'm learning php and i have a file that connects to a mysql database, i'd like to know what is the condition inside the brackets of the following "if structure" in the file, $con is an instance of the class mysqli:

if ($con->connect_errno)
{
echo "fail to connect to mysql";
}

I know that $con is invoking to connect_errno but what is conditioning if(what?){...}?

Dharman
  • 30,962
  • 25
  • 85
  • 135
lumixel
  • 167
  • 3
  • 11

1 Answers1

1

That's a status flag for mysqli handles.
See http://php.net/manual/en/mysqli.connect-errno.php

It's not a function, but a property (or a "variable" if you will). It's 0 when the connection was correctly established. It contains other values (e.g. 1043) for connection problems (such as wrong password, inavailable database server).

So the if ($con->connect_errno) check asserts that your $con instance is usable.

  • When ->connect_errno == 0 then the if block will be skipped.
  • If ->connect_errno > 0 (any other value) the error message will be printed out. (You'd more commonly see die(), trigger_error() or new Exception() than just an echo there.)

Alternatively mysqli can be configured to throw an error/exception by itself. Which would make this whole condition/block redundant.

Community
  • 1
  • 1
mario
  • 144,265
  • 20
  • 237
  • 291
  • 1
    (Btw, most people use [`PDO` rather than `mysqli`](http://php.net/manual/en/mysqlinfo.api.choosing.php) nowadays. Because that makes it much easier to handle parameter binding.) – mario Jul 05 '15 at 13:09
  • ok then it would work with if ($con->connect_errno !=0) {echo "error";} but i keep without understanding what is conditioning in if(0){echo "error";} that is the same to if ($con->connect_errno){echo "error";} – lumixel Jul 05 '15 at 14:22
  • Yes, that's the same. `if ($errno != 0) trigger_error();` – mario Jul 05 '15 at 14:39
  • but i keep without understanding what is conditioning in if(0){echo "error";} = if ($con->connect_errno){echo "error";} what is the condition? – lumixel Jul 05 '15 at 14:43
  • "When ->connect_errno == 0 then the if block will be skipped." – mario Jul 05 '15 at 14:47
  • yes i understand that but in line if ($con->connect_errno){echo "error"} i don't see any operator of comparison – lumixel Jul 05 '15 at 14:51
  • 1
    That's an implicit boolean comparison. `if ($var)` is identical to `if ($var != 0)`. – mario Jul 05 '15 at 14:51