How to work with the first row of a result set

Two more methods of the PDOStatement class

      fetch() 
      // Returns an array for the next row in the result set. This array
      // is indexed by both a string index for the column name and a numeric 
      // index for the column position. If no array is available, this 
      // method returns a FALSE value. 
      
      closeCursor()
      // Closes the cursor and frees the connection to the server so 
      // other SQL statements may be issued.
      

Code that returns a result set that contains one row

      $query = "SELECT productCode, productName, listPrice 
                FROM products 
                WHERE productID = :product_id";
      $statement = $db->prepare($query);
      $statement->bindValue(':product_id', $product_id);
      $statement->execute();
      $product = $statement->fetch();
      $statement->closeCursor();
      

Code that uses a string index to access each column

      $product_code = $product['productCode'];
      $product_name = $product['productName'];
      $product_list_price = $product['listPrice'];
      

Code that uses a numeric index to access each column

      $product_code = $product[0];
      $product_name = $product[1];
      $product_list_price = $product[2];
      

Description

Back