SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 28
  1. #1
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    MySQLi and exceptions

    Hey,

    I've created a class with mysqli methods. I'm using exceptions as my error handling. If I do this though:

    PHP Code:
    class mysql
    {
      private 
    $host;
      private 
    $username;
      private 
    $password;
      private 
    $dbname;
      private 
    $link;
      
      public function 
    __construct($host ''$username ''$password ''$dbname '')
      {
        
    $this->host $host;
        
    $this->username $username;
        
    $this->password $password;
        
    $this->connect();
      }
      
      public function 
    connect()
      {
        
    $this->link = new mysqli($this->host$this->username$this->password$this->dbname);
        if (!
    $this->link)
          Throw New 
    Exception(mysqli_error());
        return 
    $this->link;
      }

    I would expect for this to throw an exception if the connection was not made, but its not. This is what I'm doing in the index:

    PHP Code:
    try
    {
      
    $mysqli = new mysql('localhost''root''''cms222');
      echo 
    'connected';
    }
    catch (
    Exception $e)
    {
      echo 
    $e->getMessage();

    The correct database name is 'cms' but I added the extra digits to make it fail. But it doesn't, it still prints "connected".

  2. #2
    Web Professional
    Join Date
    Oct 2008
    Location
    London
    Posts
    862
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
      public function connect()
      if (!
    $this->link
    This will always evaluate to TRUE because $this->link is a MySQLi object you have just created. What you need to do is check its connection_error property:

    (As a side note: always use curly brackets with if constructs. It’s just good practice.)

    PHP Code:
      public function connect()
      {
        
    $this->link = new mysqli($this->host$this->username$this->password$this->dbname);

        if (
    $this->link->connect_error) {
          throw New 
    Exception(mysqli_error());
        }

        return 
    $this->link;
      } 

  3. #3
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I tried what you said and it's working but its also displaying an error:

    Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\Users\9three\Desktop\Server\htdocs\library\mysqli.package.php on line 23

    I'm assuming it's because im not suppressing the error messages from within the class (eg. @) ?


    BTW, is there an exception list I can view online? The only one I know is catch (Exception $e). I'm assuming (I'm a java developer) that you have more than one exception available through PHP?

    P.S. I don't use curly bracers because it's only one line. I use curly bracers for more than one line.

  4. #4
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    It merely good practice to use braces for control structures, I think that is what Paul was hinting at.

    I'm also sure you meant to say thanks too.

    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  5. #5
    Web Professional
    Join Date
    Oct 2008
    Location
    London
    Posts
    862
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by 9three View Post
    I tried what you said and it's working but its also displaying an error:

    Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\Users\9three\Desktop\Server\htdocs\library\mysqli.package.php on line 23

    I'm assuming it's because im not suppressing the error messages from within the class (eg. @) ?
    Never use error suppression. You should handle errors, not suppress them.

    You should use $this->link->connect_error instead of mysqli_error().

    Quote Originally Posted by 9three View Post
    BTW, is there an exception list I can view online? The only one I know is catch (Exception $e). I'm assuming (I'm a java developer) that you have more than one exception available through PHP?
    Exception is the only native exception class. You can, however, extend it and build your own.

    Quote Originally Posted by 9three View Post
    P.S. I don't use curly bracers because it's only one line. I use curly bracers for more than one line.
    Yes, I know. It’s bad practice. First of all the code is more readable with braces even if there’s only one line. Also, you won’t have to worry that you forget to add braces if you want to add another line in the future. Always use braces.

  6. #6
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Got it, it's working now. I forgot to change the exception to mysqli_connect_error().

    I didn't mean any disrespect about the curly bracers.

    As always,

    Thanks for the help

  7. #7
    Web Professional
    Join Date
    Oct 2008
    Location
    London
    Posts
    862
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by 9three View Post
    Got it, it's working now. I forgot to change the exception to mysqli_connect_error().
    You shouldn’t use procedural access to MySQLi (it’s deprecated). Use OO manner instead: MySQLi->connect_error (so in your code that would be $this->link->connect_error).

  8. #8
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by decowski View Post
    You shouldn’t use procedural access to MySQLi (it’s deprecated). Use OO manner instead: MySQLi->connect_error (so in your code that would be $this->link->connect_error).
    thanks for the advice, good stuff.

  9. #9
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    BTW, is there an exception list I can view online? The only one I know is catch (Exception $e). I'm assuming (I'm a java developer) that you have more than one exception available through PHP?

    eg. in java you have all kinds of different exceptions:

    Exception e
    FileNotFoundException e
    etc

  10. #10
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    As far as I'm aware, most native PHP objects throw a generic Exception. Although there is nothing stopping you catching the original exception and throw an extending exception which is a bit more descriptive.

    Exceptions in PHP are relatively new, and therefore appear quite lacking compared to other more mature OOP languages.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  11. #11
    Web Professional
    Join Date
    Oct 2008
    Location
    London
    Posts
    862
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Look above (post #5). I answered it there.

  12. #12
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SilverBulletUK View Post
    As far as I'm aware, most native PHP objects throw a generic Exception. Although there is nothing stopping you catching the original exception and throw an extending exception which is a bit more descriptive.

    Exceptions in PHP are relatively new, and therefore appear quite lacking compared to other more mature OOP languages.
    thanks

    sorry deco i didn't see that part of your post.

  13. #13
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey,

    I'm having an issue. It's always returning "connected" whether the data base name is correct or not.

    PHP Code:
      public function connect()
      {
        
    $this->link = new mysqli($this->host$this->username$this->password$this->dbname);
        if (
    $this->link->connect_error) { // Error returned true
          
    Throw New Exception($this->link->connect_error);
        }
        return 
    $this->link//No exception was thrown, return $this->link
      

    This is the index:

    PHP Code:
    try {
      
    $mysqli = new mysql('localhost''root''''cms2');
      echo 
    'Connected';
    }
    catch (
    Exception $e) {
      echo 
    $e;

    the database name is actually 'cms' not 'cms2'. But either way it prints "connected"

    If I do !$this->link->connect_error it returns an exception

    Code:
    exception 'Exception' in C:\Users\9three\Desktop\Server\htdocs\library\mysqli.package.php:23 Stack trace: #0 C:\Users\9three\Desktop\Server\htdocs\library\mysqli.package.php(16): mysql->connect() #1 C:\Users\9three\Desktop\Server\htdocs\library\index.php(12): mysql->__construct('localhost', 'root', '', 'cms2') #2 {main}
    Again, whether I use 'cms' or 'cms2' it still throws this exception. Now I don't know why, the syntax looks correct in the class.

  14. #14
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Anyone ?

  15. #15
    Web Professional
    Join Date
    Oct 2008
    Location
    London
    Posts
    862
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try mysqli_connect_error() instead. Apparently MySQLi->connect_error was broken until PHP 5.2.9.

  16. #16
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If I use $this->link->mysqli_connnect_error() I can an error of undefined method.

    If I do $this->link->connect_error and I change the exception to mysqli_connect_error() I'm back to the same thing

  17. #17
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    This appears to work just fine...

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

    try
    {
        
    $oDB = new OurDatabase();
    }
    catch(
    Exception $oException)
    {
        echo 
    $oException->getMessage();    
    }
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  18. #18
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah you're using mysqli_connect_errno which returns a int. good thinking.

    So the preferred way is using $mysqli->connect_error ? But it's not working right as of 5.2.9?

    thanks

  19. #19
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by 9three View Post
    Ah you're using mysqli_connect_errno which returns a int. good thinking.

    So the preferred way is using $mysqli->connect_error ? But it's not working right as of 5.2.9?

    thanks
    It's not working for me using 5.2.6, so quite possibly.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  20. #20
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ah cool thanks everyone

  21. #21
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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".

  22. #22
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Certainly did.

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

    Your modified code please.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  23. #23
    Non-Member
    Join Date
    Oct 2008
    Posts
    372
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I didn't modify anything lol, straight copy and paste.

    PHP Code:
    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.

  24. #24
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    Off Topic:


    Quote Originally Posted by decowski View Post
    Exception is the only native exception class. You can, however, extend it and build your own.
    The native exceptions are Exception and 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

    Salathe
    Software Developer and PHP Manual Author.

  25. #25
    Web Professional
    Join Date
    Oct 2008
    Location
    London
    Posts
    862
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Off Topic:


    Quote Originally Posted by Salathe View Post
    The native exceptions are Exception and ErrorException.
    *holds head in shame*

    ErrorException, of course.



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •