質問

I have function :

function dbConnect($usertype, $connectionType = 'mysqli') {

   // some code hare

   return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}

but when I try this:

$conn = dbConnect('read');
$result = $conn->query('SELECT * FROM images');

function dosn't return anything and it say :

Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\phpsols\mysql\mysqli.php on line 10

but it works this way(without die())

return new mysqli($host, $user, $pwd, $db);
役に立ちましたか?

解決

The [..] or die() construct leads to funny behaviour in conjunction with the return statement: The whole thing is interpreted as a boolean expression.

And because new mysqli will never be false, the "die" is never processed, and thus, your function returns true instead of a newly created instance of mysqli.

If you still would like to use or die(), do this:

$result = new mysqli($host, $user, $pwd, $db) ;
if (!$result) die ("Can't open database.");
return $result;

他のヒント

You can try this:

function dbConnect($usertype, $connectionType = 'mysqli') {

   // some code hare
   try {
       return new mysqli($host, $user, $pwd, $db);
   } catch(Exception $e) {
       die ('Cannot open database');
   }
}

aside from this funny one-liner problem, your idea of error handling is all wrong. Sadly, it was copy-pasted to other answer as well.

Here is the right code

$mysqli = new mysqli($host, $user, $pwd, $db);
if ( mysqli_connect_errno() )
{
    throw new Exception(mysqli_connect_errno()." ".mysqli_connect_error());
}
return $mysqli;

Honestly, this die ('something'); thing is a childhood disease of PHP. Time to grow up a little.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top