Learning PDO

Discussion in 'PHP' started by swift_lee_o, Mar 26, 2013.

  1. #1
    Okay, so I'm trying to learn PDO. Here is what I have made so far. It is a simple db fetch for a first name in my database (test). It is supposed to fetch the first name for any user that's first name matches $_GET['name']. It works correctly, but is there anything that I should be aware of? Such as a security flaw or a better way to accomplish what I want?

    This is my first time ever trying PDO so any comments or help would and always will be welcome. Thanks in advance.

    
     
    <?php
     
      $dsn      = 'mysql:dbname=test;host=localhost';
      $username = 'user';
      $password = 'pass';
     
      $dbh = new PDO($dsn, $username, $password);
     
      $stmt = $dbh->prepare('SELECT `fname`
                                  FROM `users`
                                  WHERE `fname` = :fname');
      $stmt->bindParam(':fname', $_GET['name']);
      $stmt->execute();
     
      while($user = $stmt->fetch()){
     
          echo $user['fname'];
     
      }
     
    ?>
    PHP:

     
    swift_lee_o, Mar 26, 2013 IP
  2. HuggyStudios

    HuggyStudios Well-Known Member

    Messages:
    724
    Likes Received:
    20
    Best Answers:
    26
    Trophy Points:
    165
    #2
    You don't need to worry about SQL injections as the statements are prepared. You should be on the look out for a possible XSS problem if you display that $_GET variable.

    Your'e best using a framework like Code Igniter it has a great database system and xss protection etc.
     
    HuggyStudios, Mar 26, 2013 IP