MySQLi and exceptions

Did you happen to test out that code? I just copy and pasted and it doesn’t work. If I print a string “connected” in the try block, it will always say “connected”.

Certainly did.

So you say you just ‘copy & pasted’ my example, modified it, then blame my example because your modified code doesn’t work? :stuck_out_tongue:

Your modified code please.

I didn’t modify anything lol, straight copy and paste.


class OurDatabase
{
    protected $oConnection = null;
    
    public function __construct()
    {
        $this->oConnection = @new mysqli('localhost', 'root', '', 'mysql');
        if(mysqli_connect_errno() > 0)
        {
            throw new Exception(sprintf('Cannot connect to database: %s', mysqli_connect_error()));
        }
    }
}

try
{
    $oDB = new OurDatabase();
    echo 'connected';
}
catch(Exception $oException)
{
    echo $oException->getMessage();    
}

Same exact thing I only added the connected.

Off Topic:

The native exceptions are Exception and [URL=“http://php.net/class.errorexception”]ErrorException. The SPL extension also comes with a number of more useful exceptions (http://php.net/spl.exceptions):

  • BadFunctionCallException
  • BadMethodCallException
  • DomainException
  • InvalidArgumentException
  • LengthException
  • LogicException
  • OutOfBoundsException
  • OutOfRangeException
  • OverflowException
  • RangeException
  • RuntimeException
  • UnderflowException
  • UnexpectedValueException
Off Topic:

holds head in shame

ErrorException, of course.

very nice thanks for that.

So you’ve changed the credentials to something which you know to be incorrect and it still says connected?

If so, you’ve got me! :confused:

I changed the parameters to something that would be false but it doesn’t throw an exception. Just says “connected”.

EDIT:
oh wow I didn’t even notice that I actually have a database named “mysql”. I guess that came with XAMPP. duuuuhhh

It’s working like a charm now, thanks!