Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    892
    Thanks
    301
    Thanked 2 Times in 2 Posts

    Question Difference beween if() and try /catch()

    Hi

    Please consider the two code snippets. Can someone pls tell me which one is better and why?


    Code:
    $q = "insert into...";
    mysql_query($q);
    
    if(mysql_affected_rows()>0){
       $id = mysql_insert_id();
    }else{
       $id = false;
    }
    
    if( ! $id ){
      echo 'Something went wrong: ' .  mysql_error();
    }
    AND

    Code:
    $q = "insert into...";
    
    try{
      mysql_query($q);
    }catch(Exception $e){
      echo echo 'Something went wrong: ' .  $e->getMessage();
    }

    From my understanding, the first one actually tells you if there was a problem in running the query.


    Many thanks in advance
    Last edited by phantom007; 04-07-2013 at 03:20 AM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    The second one won't work. mysql_query isn't capable of throwing an exception so therefore you cannot catch it. The only option you have there is to use an if.

    Exceptions are used typically with objects where a condition has occurred and the method handling it refuses to do anything with it, so instead it throws an exception and lets the caller deal with it. The is the more ideal approach than how PHP has traditionally worked, which is to use a best-attempt-and-keep-going-if-you-can approach. It's quite annoying actually, so I'm glad that we got exceptions added with 5.0.
    You can throw in procedural as well, but IMO it doesn't make a lot of sense since you have to catch into an object anyway.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #3
    Regular Coder
    Join Date
    Jun 2006
    Location
    UK
    Posts
    892
    Thanks
    301
    Thanked 2 Times in 2 Posts
    Thanks very much for the explanation.

    Appreciate it.


  •  

    Posting Permissions

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