SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot TheMonk's Avatar
    Join Date
    Oct 2005
    Location
    Canada
    Posts
    143
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Query construction question...

    I'm reading sitepoint's PHP anthology book and they're discussing PDO. At one point they discuss the prepare and execute methods. Here's the code:

    PHP Code:
    <?php
    // make the DSN
    $dsn 'mysql:host=localhost;dbname=world;';
    $user 'user';
    $password 'secret';

    $country 'USA';
    // try to make the connection to the database
    try
    {
      
    $dbh = new PDO($dsn$user$password);
      
    $sql 'Select * from city where CountryCode =:country';
      
    $dbh->setAttribute(PDO::ATTR_ERRMODE
          
    PDO::ERRMODE_EXCEPTION);
      
    $stmt $dbh->prepare($sql);
      
    $stmt->bindParam(':country'$countryPDO::PARAM_STR);
      
    $stmt->execute();
      while (
    $row $stmt->fetch(PDO::FETCH_ASSOC)) {
        print 
    $row['Name'] . "\t";
        print 
    $row['CountryCode'] . "\t";
        print 
    $row['Population'] . "\n";
      }

    // if there is a problem we can handle it here
    catch (PDOException $e)
    {
      echo 
    'PDO Exception Caught.  ';
      echo 
    'Error with the database: <br />';
      echo 
    'SQL Query: '$sql;
      echo 
    'Error: ' $e->getMessage();
    }
    ?>
    Most of it makes sense however there are two lines I don't quite get.

    PHP Code:
      $sql 'Select * from city where CountryCode =:country'
    and

    PHP Code:
    $stmt->bindParam(':country'$countryPDO::PARAM_STR); 
    In both of these lines the variable "country" is prefixed with a colon, for example ":country". What does the colon represent and how does it affect the statement?

    Thanks!

  2. #2
    SitePoint Zealot TheMonk's Avatar
    Join Date
    Oct 2005
    Location
    Canada
    Posts
    143
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok well this is a classic case of RTFM. I'm basically jumping ahead on the book and I think that's what confused me.

    So I understand that :country is a placeholder and the real value is added when PDO execute is called. So here's my next question, why would you bind a parameter this way? Is it so you can reuse the query statement multiple times and simply change the parameter?


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
  •