downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

PDOStatement->fetchColumn> <PDOStatement->fetch
[edit] Last updated: Fri, 17 May 2013

view this page in

PDOStatement->fetchAll

(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement->fetchAllSonuç kümesinin tüm satırlarını içeren bir dizi döndürür

Açıklama

array PDOStatement::fetchAll ([ int $alım_tarzı = PDO::FETCH_BOTH [, int $sütunnum [, array $değiştirgeler = array() ]]] )

Değiştirgeler

alım_tarzı

PDOStatement::fetch() yönteminde açıklandığı gibi döndürülen dizinin içeriğini belirleyen sabit. PDO::FETCH_BOTH öntanımlıdır.

Sonuç kümesindeki tek bir sütunun tüm değerleri içeren bir dizi döndürmek için PDO::FETCH_COLUMN belirtin. Bu durumda hangi sütunun içeriğinin alınacağını sütunnum ile belirtin.

Sonuç kümesindeki tek bir sütunun eşsiz değerleri içeren bir dizi döndürmek için PDO::FETCH_COLUMN ile PDO::FETCH_UNIQUE sabitini bit seviyesinde VEYAlayın.

Belirtilen sütunun değerlerine göre gruplanmış bir ilişkisel dizi döndürmek için PDO::FETCH_COLUMN ile PDO::FETCH_GROUP sabitini bit seviyesinde VEYAlayın.

sütunnum

alım_tarzı değiştirgesinde PDO::FETCH_COLUMN belirtildiği takdirde alınacak sütun numarası burada belirtilir. İlk sütunun indisi 0 olup öntanımlı değerdir.

değiştirgeler

Bu dizinin elemanları kurucuya değiştirge olarak aktarılır..

Dönen Değerler

Sonuç kümesinde kalan satırların tümünü bir dizi olarak döndürür. Dizinin her elemanı birer satır içerir ve bu satır elemanları sütun değerlerini içeren bir dizi ya da sütun isimlerinin özelliklere karşı düştüğü bir nesne içerir.

Büyük sonuç kümelerini almak için bu yöntemi kullanmak sistem ve muhtemelen ağ kaynaklarından aşırı taleplere yol açar. Tüm veriyi alıp PHP ile işleme tabi tutmak yerine sonuç kümeleri üzerinde işlem yapmak için veritabanı sunucusunu kullanmak daha iyi olabilir. Örneğin, SQL'de WHERE ve SORT BY yan tümcelerini kullanarak, PHP'de işleme sokmadan önce sonuç kümesini küçültebilirsiniz.

Örnekler

Örnek 1 - Bir sonuç kümesinde kalan tüm satırları almak

<?php
$sth 
$dbh->prepare("SELECT ad, renk FROM meyveler");
$sth->execute();

/* Sonuç kümesindeki tüm satırları alalım */
print("Sonuç kümesindeki tüm satırlar:\n");
$result $sth->fetchAll();
print_r($result);
?>

Yukarıdaki örneğin çıktısı:

Sonuç kümesindeki tüm satırlar:
Array
(
    [0] => Array
        (
            [AD] => armut
            [0] => armut
            [RENK] => yeşil
            [1] => yeşil
        )

    [1] => Array
        (
            [AD] => ahududu
            [0] => ahududu
            [RENK] => mor
            [1] => mor
        )

)

Örnek 2 - Sonuç kümesinden tek bir sütunun tüm değerlerini almak

Aşağıdaki örnekte, SQL deyimi her satırda çok sayıda sütun döndürse bile bu sonuç kümesinden tek bir sütunun tüm değerlerinin nasıl alınacağı gösterilmiştir.

<?php
$sth 
$dbh->prepare("SELECT isim, renk FROM meyveler");
$sth->execute();

/* İlk sütunun tüm değerlerini alalım */
$result $sth->fetchAll(PDO::FETCH_COLUMN0);
var_dump($result);
?>

Yukarıdaki örneğin çıktısı:

Array(3)
(
    [0] =>
    string(5) => elma
    [1] =>
    string(4) => armut
    [2] =>
    string(10) => ahududu
)

Örnek 3 - Tüm değerleri tek bir sütuna göre gruplamak

Aşağıdaki örnekte, sonuç kümesindeki belli bir sütunun değerlerine göre gruplanmış bir ilişkisel dizini nasıl döndürüleceği gösterilmiştir. Dizi üç anahtar içerir: Elma ve armut iki farklı renk içeren iki dizi olarak ahududu ise tek renk içeren bir dizi olarak döndürülür.

<?php
$insert 
$dbh->prepare("INSERT INTO fruit(isim, renk) VALUES (?, ?)");
$insert->execute(array('elma''yeşil'));
$insert->execute(array('armut''sarı'));

$sth $dbh->prepare("SELECT isim, renk FROM meyveler");
$sth->execute();

/* Değerleri ilk sütuna göre gruplayalım */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>

Yukarıdaki örneğin çıktısı:

array(3) {
  ["elma"]=>
  array(2) {
    [0]=>
    string(5) "yeşil"
    [1]=>
    string(3) "kırmızı"
  }
  ["armut"]=>
  array(2) {
    [0]=>
    string(5) "yeşil"
    [1]=>
    string(6) "sarı"
  }
  ["ahududu"]=>
  array(1) {
    [0]=>
    string(5) "mor"
  }
}

Ayrıca Bakınız



PDOStatement->fetchColumn> <PDOStatement->fetch
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes PDOStatement->fetchAll - [13 notes]
up
2
harlequin2 at gmx dot de
4 years ago
There is also another fetch mode supported on Oracle and MSSQL:
PDO::FETCH_ASSOC

> fetches only column names and omits the numeric index.

If you would like to return all columns from an sql statement with column keys as table headers, it's as simple as this:

<?php
$dbh
= new PDO("DS", "USERNAME", "PASSWORD");
$stmt = $dbh->prepare("SELECT * FROM tablename");
$stmt->execute();
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
// open the table
print "<table wdith=\"100%\">\n";
print
"<tr>\n";
// add the table headers
foreach ($arrValues[0] as $key => $useless){
    print
"<th>$key</th>";
}
print
"</tr>";
// display data
foreach ($arrValues as $row){
    print
"<tr>";
    foreach (
$row as $key => $val){
        print
"<td>$val</td>";
    }
    print
"</tr>\n";
}
// close the table
print "</table>\n";
?>
up
1
Anonymous
1 year ago
Note that fetchAll() can be extremely memory inefficient for large data sets. My memory limit was set to 160 MB this is what happened when I tried:

<?php
$arr
= $stmt->fetchAll();
// Fatal error: Allowed memory size of 16777216 bytes exhausted
?>

If you are going to loop through the output array of fetchAll(), instead use fetch() to minimize memory usage as follows:

<?php
while ($arr = $stmt->fetch()) {
    echo
round(memory_get_usage() / (1024*1024),3) .' MB<br />';
   
// do_other_stuff();
}
// Last line for the same query shows only 28.973 MB usage
?>
up
1
Anonymous
5 years ago
If no rows have been returned, fetchAll returns an empty array.
up
0
mxrgus
3 years ago
In method body:

return $pstmt->fetchAll() or die("bad");

will not return correct value, but "1" instead.
up
0
stas at metalinfo dot ru
6 years ago
Note, that you can use PDO::FETCH_COLUMN|PDO::FETCH_GROUP pair only while selecting two columns, not like DB_common::getAssoc(), when grouping is set to true.
up
0
ramon at monztro dot com
11 months ago
If you are trying to call PDOStatement::fetchAll and is not getting the result set as expected (empty instead), check if you called PDOStatement::execute first.

Remember PDOStatement::fetchAll does not execute the query, it just mounts the array.

:)
up
0
Hayley Watson
1 year ago
If you use the PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE flags to map columns to object properties, fetchAll() will use any __set() method your object has when carrying out the mapping.
up
0
Dennis
2 years ago
Error:
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

If you're using something like:

while ($row = $query->fetchObject()) {
    [...]
}

try using this instead:

$rows = $query->fetchAll(PDO::FETCH_CLASS, 'ArrayObject');

foreach ($rows as $row) {
    [...]
}
up
0
esw at pixeloution dot removeme dot com
3 years ago
Interestingly enough, when you use fetchAll, the constructor for your object is called AFTER the properties are assigned. For example:

<?php
class person {
    public
$name;

    function
__construct() {
      
$this->name = $this->name . " is my name.";
    }
}

# set up select from a database here with PDO
$obj = $STH->fetchALL(PDO::FETCH_CLASS, 'person');
?>

Will result in ' is my name' being appended to all the name columns. However if you call it slightly differently:

<?php
$obj
= $obj = $STH->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'person');
?>

Then the constructor will be called before properties are assigned. I can't find this documented anywhere, so I thought it would be nice to add a note here.
up
0
Daniel Hofmann
4 years ago
PLEASE BE AWARE: If you do an OUTER LEFT JOIN and set PDO FetchALL to PDO::FETCH_ASSOC, any primary key you used in the OUTER LEFT JOIN will be set to a blank if there are no records returned in the JOIN.

For example:
<?php
//query the product table and join to the image table and return any images, if we have any, for each product
$sql = "SELECT * FROM product, image
LEFT OUTER JOIN image ON (product.product_id = image.product_id)"
;

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($array);
?>

The resulting array will look something like this:

Array
(
    [0] => Array
        (
            [product_id] =>
            [notes] => "this product..."
            [brand] => "Best Yet"
            ...

The fix is to simply specify your field names in the SELECT clause instead of using the * as a wild card, or, you can also specify the field in addition to the *. The following example returns the product_id field correctly:

<?php
$sql
= "SELECT *, product.product_id FROM product, image
LEFT OUTER JOIN image ON (product.product_id = image.product_id)"
;

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($array);
?>

The resulting array will look something like this:

Array
(
    [0] => Array
        (
            [product_id] => 3
            [notes] => "this product..."
            [brand] => "Best Yet"
            ...
up
0
Ant P.
4 years ago
You might find yourself wanting to use FETCH_GROUP and FETCH_ASSOC at the same time, to get your table's primary key as the array key:
<?php
// $stmt is some query like "SELECT rowid, username, comment"
$results = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

// It does work, but not as you might expect:
$results = array(
   
1234 => array(0 => array('username' => 'abc', 'comment' => '[...]')),
   
1235 => array(0 => array('username' => 'def', 'comment' => '[...]')),
);

// ...but you can at least strip the useless numbered array out easily:
$results = array_map('reset', $results);
?>
up
0
davey at php dot net
4 years ago
When passing PDO::FETCH_CLASS as the first argument, this method will accept the class name as the second option:

<?php
$query
= $pdo->prepare($sql);

$result = $query->execute($values);

if (
$result && $query->rowCount() > 0) {
   
$records = $query->fetchAll(PDO::FETCH_CLASS, 'Some_Class');
   
// $record is now an array of Some_Class objects
}
?>

- Davey
up
0
mrshelly at hotmail dot com
4 years ago
PHP fetchAll Data From SQL Server 2005
if field's data type is varchar(nvarchar), only fetch 255 chars. but the "text" data type is ok.

so, notice! to change the 'varchar' or 'nvarchar' (length > 255) to 'text' data type..

hope to help u.

<?php

$user
= 'sa';
$pass = 'pass';

$conn = new PDO('mssql:host=127.0.0.1; dbname=tempdb;', $user, $pass);

$mainSQL = "SELECT field_varchar, field_text FROM table1";
$sth = $conn->prepare($mainSQL);
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$retRows = $sth->fetchAll();
// the field_varchar field only to fetch 255 chars(max)
// the field_text is ok.

var_dump($retRows);

unset(
$sth); unset($conn);

?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites