Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : PDO Functions : PDO->query()

PDO->query()

Executes an SQL statement, returning a result set as a PDOStatement object ()

Example 1765. Demonstrate PDO::query

A nice feature of PDO->query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement.

<?php
function getFruit($conn) {
   
$sql = 'SELECT name, colour, calories FROM fruit ORDER BY name';
   foreach (
$conn->query($sql) as $row) {
       print
$row['NAME'] . "\t";
       print
$row['COLOUR'] . "\t";
       print
$row['CALORIES'] . "\n";
   }
}
?>

The above example will output:

apple   red     150
banana  yellow  250
kiwi    brown   75
lemon   yellow  25
orange  orange  300
pear    green   150
watermelon      pink    90

Code Examples / Notes » pdo_query

fredrik

The handling of errors by this function is controlled by the attribute PDO::ATTR_ERRMODE.
Use the following to make it throw an exception:
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>


nicobn

Please note that when Query() fails, it does not return a PDOStatement object . It simply returns false.

ravo

I struggled with this trying to figure out why I couldn't return a single row using a simple query. This may or may be obvious but you have to use PDOstatement functions of the result of a PDO->query(). This took me a while to figure out since it is a far cry from the query functions of old.
<?php
$connection = new pdo("sqlite:file.sq3");
$query="SELECT * FROM table";
$result = $connection->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
print_r($row);
?>


Change Language


Follow Navioo On Twitter
PDO->beginTransaction()
PDO->commit()
PDO->__construct()
PDO->errorCode()
PDO->errorInfo()
PDO->exec()
PDO->getAttribute()
PDO->getAvailableDrivers()
PDO->lastInsertId()
PDO->prepare()
PDO->query()
PDO->quote()
PDO->rollBack()
PDO->setAttribute()
PDOStatement->bindColumn()
PDOStatement->bindParam()
PDOStatement->bindValue()
PDOStatement->closeCursor()
PDOStatement->columnCount()
PDOStatement->errorCode()
PDOStatement->errorInfo()
PDOStatement->execute()
PDOStatement->fetch()
PDOStatement->fetchAll()
PDOStatement->fetchColumn()
PDOStatement->fetchObject()
PDOStatement->getAttribute()
PDOStatement->getColumnMeta()
PDOStatement->nextRowset()
PDOStatement->rowCount()
PDOStatement->setAttribute()
PDOStatement->setFetchMode()
eXTReMe Tracker