php PDO question

Discussion in 'PHP' started by plussy, Sep 26, 2012.

  1. #1
    just starting to use PDO in php and was wondering if this is the right way to do it and if it is secure or if I still need to do any escaping (thought the prepare will take care of this but might be wrong)?
                    
    function emailAvailable ($email) {
      
       // ensure database connection is accessible
       global $dbh;
       
       // prepare sql query to see if email address already exists
       $stmt = $dbh->prepare('SELECT COUNT(*) AS `tot` FROM `user` WHERE `email`=:email');    
       
       // execute query with provided data
       $stmt->execute(array(':email' => $email));
       
       // get the result
       $result = $stmt->fetch(PDO::FETCH_ASSOC);
       
       if ($result['tot'] > 0) {
        return false;
       }
       else {
        return true;
       }
      }
    
    PHP:

     
    plussy, Sep 26, 2012 IP
  2. GMF

    GMF Well-Known Member

    Messages:
    855
    Likes Received:
    113
    Best Answers:
    19
    Trophy Points:
    145
    #2
    I haven't used PDO to connect to a database yet, but I know some articles that should provide some help (also regarding escaping)

    
    http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/?search_index=1
    http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/?search_index=2
    http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/?search_index=3
    
    Code (markup):
    Regarding escaping:

    Whenever a user can input something it has to be escaped. No matter how simple and obvious it seems - escape it
     
    GMF, Sep 26, 2012 IP
  3. plussy

    plussy Peon

    Messages:
    152
    Likes Received:
    5
    Best Answers:
    9
    Trophy Points:
    0
    #3
    Thanks,

    I thought the prepare statement would take care of escaping. But by the look of it I was wrong.

    Thanks for the links.
     
    plussy, Sep 26, 2012 IP
  4. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #4
    By using placeholders in PDO you are protecting your code from SQL Injection.
     
    NetStar, Sep 29, 2012 IP
  5. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #5
    You thought correctly. You do not need to quote Prepared Statements. From PDO::prepare manual:

    The other alternative is PDO query and PDO quote, which is faster than prepared statements.
     
    ThePHPMaster, Sep 29, 2012 IP