11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 31 • INTRODUCING PDOwww.it-ebooks.infoFetching a Single ColumnThe fetchColumn() method returns a single column value located in the next row of the result set. Itsprototype follows:string PDOStatement::fetchColumn([int column_number])The column reference, assigned to column_number, must be specified according to its numericaloffset in the row, which begins at 0. If no value is set, fetchColumn() returns the value found in the firstcolumn. Oddly enough, it’s impossible to retrieve more than one column in the same row using thismethod, as each call moves the row pointer to the next position; therefore, consider using fetch()should you need to do so.The following example both demonstrates fetchColumn() and shows how subsequent calls to themethod move the row pointer:// Execute the query$result = $dbh->query('SELECT sku, title FROM products ORDER BY title');// Fetch the first row first column$sku = $result->fetchColumn(0);// Fetch the second row second column$title = $result->fetchColumn(1);// Output the data.echo "Product: $title ($sku)";The resulting output follows. Note that the product title and SKU don’t correspond to the correctvalues as provided in the sample table because, as mentioned, the row pointer advances with each callto fetchColumn(); therefore, be wary when using this method.Product: AquaSmooth Toothpaste (PO988932)Setting Bound ColumnsIn the previous section, you learned how to set the fetch_style parameter in the fetch() and fetchAll()methods to control how the result set columns will be made available to your script. You were probablyintrigued by the PDO_FETCH_BOUND setting because it seems to let you avoid an additional step altogetherwhen retrieving column values by just assigning them automatically to predefined variables. Indeed thisis the case, and it’s accomplished using the bindColumn() method.The bindColumn() method is used to match a column name to a desired variable name, which, uponeach row retrieval, will result in the corresponding column value being automatically assigned to thevariable. Its prototype follows:boolean PDOStatement::bindColumn(mixed column, mixed &param [, int type[, int maxlen [, mixed driver_options]]])624

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!