Php pdo fetch all array

PDOStatement::fetchAll

Определяет содержимое возвращаемого массива. Подробней можно узнать из документации к методу PDOStatement::fetch() . По умолчанию параметр принимает значение PDO::ATTR_DEFAULT_FETCH_MODE (которое в свою очередь имеет умолчание PDO::FETCH_BOTH )

Чтобы извлечь значения только одного столбца, передайте в качестве значения этого параметра константу PDO::FETCH_COLUMN . С помощью параметра column-index можно задать столбец, из которого требуется извлечь данные.

Если требуется извлечь только уникальные строки одного столбца, нужно передать побитовое ИЛИ констант PDO::FETCH_COLUMN и PDO::FETCH_UNIQUE .

Чтобы получить ассоциативный массив строк сгруппированный по значениям определенного столбца, нужно передать побитовое ИЛИ констант PDO::FETCH_COLUMN и PDO::FETCH_GROUP .

  • PDO::FETCH_COLUMN : Будет возвращен указанный столбец. Индексация столбцов начинается с 0.
  • PDO::FETCH_CLASS : Будет создан и возвращен новый объект указанного класса. Свойствам объекта будут присвоены значения столбцов, имена которых совпадут с именами свойств.
  • PDO::FETCH_FUNC : Будут возвращены результаты вызовов указанной функции. Данные каждой строки результирующего набора будут передаваться в эту функцию.

Аргументы конструктора класса. Для случаев, когда параметру fetch_style присвоено значение PDO::FETCH_CLASS .

Возвращаемые значения

PDOStatement::fetchAll() возвращает массив, содержащий все оставшиеся строки результирующего набора. Массив представляет каждую строку либо в виде массива значений одного столбца, либо в виде объекта, имена свойств которого совпадают с именами столбцов. В случае, если нет результатов, то будет возвращен пустой массив. В случае ошибки возвращается FALSE .

Использование этого метода для извлечения строк больших результирующих наборов может пагубно сказаться на производительности системы и сетевых ресурсов. Вместо извлечения всех данных и их обработки в PHP рекомендуется использовать встроенные средства СУБД. Например, использование выражений WHERE и ORDER BY языка SQL может уменьшить размеры результирующего набора.

Примеры

Пример #1 Извлечение всех оставшихся строк результирующего набора

$sth = $dbh -> prepare ( «SELECT name, colour FROM fruit» );
$sth -> execute ();

/* Извлечение всех оставшихся строк результирующего набора */
print( «Извлечение всех оставшихся строк результирующего набора:\n» );
$result = $sth -> fetchAll ();
print_r ( $result );
?>

Результатом выполнения данного примера будет что-то подобное:

Извлечение всех оставшихся строк результирующего набора: Array ( [0] => Array ( [NAME] => pear [0] => pear [COLOUR] => green [1] => green ) [1] => Array ( [NAME] => watermelon [0] => watermelon [COLOUR] => pink [1] => pink ) )

Пример #2 Извлечение всех значений одного столбца результирующего набора

В следующем примере показано, как извлечь из результирующего набора значения только одного столбца, даже если строки содержат значения нескольких столбцов.

$sth = $dbh -> prepare ( «SELECT name, colour FROM fruit» );
$sth -> execute ();

/* Извлечение всех значений первого столбца */
$result = $sth -> fetchAll ( PDO :: FETCH_COLUMN , 0 );
var_dump ( $result );
?>

Читайте также:  text-transform

Результатом выполнения данного примера будет что-то подобное:

Array(3) ( [0] => string(5) => apple [1] => string(4) => pear [2] => string(10) => watermelon )

Пример #3 Группировка строк по значениям одного столбца

В следующем примере показано, как получить ассоциативный массив строк результирующего набора, сгруппированных по значениям указанного столбца. Массив содержит три ключа: значения apple и pear являются массивами, содержащими два разных цвета; в тоже время watermelon будет массивом, содержащим только один цвет.

$insert = $dbh -> prepare ( «INSERT INTO fruit(name, colour) VALUES (?, ?)» );
$insert -> execute (array( ‘apple’ , ‘green’ ));
$insert -> execute (array( ‘pear’ , ‘yellow’ ));

$sth = $dbh -> prepare ( «SELECT name, colour FROM fruit» );
$sth -> execute ();

/* Группируем записи по значениям первого столбца */
var_dump ( $sth -> fetchAll ( PDO :: FETCH_COLUMN | PDO :: FETCH_GROUP ));
?>

Результатом выполнения данного примера будет что-то подобное:

array(3) < ["apple"]=>array(2) < [0]=>string(5) "green" [1]=> string(3) "red" > ["pear"]=> array(2) < [0]=>string(5) "green" [1]=> string(6) "yellow" > ["watermelon"]=> array(1) < [0]=>string(5) "green" > >

Пример #4 Создание объекта для каждой строки

В следующем примере показано поведение метода в режиме выборки PDO::FETCH_CLASS .

$sth = $dbh -> prepare ( «SELECT name, colour FROM fruit» );
$sth -> execute ();

$result = $sth -> fetchAll ( PDO :: FETCH_CLASS , «fruit» );
var_dump ( $result );
?>

Результатом выполнения данного примера будет что-то подобное:

array(3) < [0]=>object(fruit)#1 (2) < ["name"]=>string(5) "apple" ["colour"]=> string(5) "green" > [1]=> object(fruit)#2 (2) < ["name"]=>string(4) "pear" ["colour"]=> string(6) "yellow" > [2]=> object(fruit)#3 (2) < ["name"]=>string(10) "watermelon" ["colour"]=> string(4) "pink" > >

Пример #5 Вызов функции для каждой строки

В следующем примере показано поведение метода в режиме выборки PDO::FETCH_FUNC .

$sth = $dbh -> prepare ( «SELECT name, colour FROM fruit» );
$sth -> execute ();

$result = $sth -> fetchAll ( PDO :: FETCH_FUNC , «fruit» );
var_dump ( $result );
?>

Результатом выполнения данного примера будет что-то подобное:

array(3) < [0]=>string(12) "apple: green" [1]=> string(12) "pear: yellow" [2]=> string(16) "watermelon: pink" >

Смотрите также

  • PDO::query() — Выполняет SQL запрос и возвращает результирующий набор в виде объекта PDOStatement
  • PDOStatement::fetch() — Извлечение следующей строки из результирующего набора
  • PDOStatement::fetchColumn() — Возвращает данные одного столбца следующей строки результирующего набора
  • PDO::prepare() — Подготавливает запрос к выполнению и возвращает ассоциированный с этим запросом объект
  • PDOStatement::setFetchMode() — Задает режим выборки по умолчанию для объекта запроса

Источник

fetchAll

Summary: in this tutorial, you’ll learn how to use the PHP fetchAll() method of the PDOStatement object to return an array containing all rows of a result set.

Introduction to the PHP fetchAll() method

The fetchAll() is a method of the PDOStatement class. The fetchAll() method allows you to fetch all rows from a result set associated with a PDOStatement object into an array.

Читайте также:  Array no java script

The following shows the syntax of the fetchAll() method:

public function fetchAll(int $mode = PDO::FETCH_DEFAULT): arrayCode language: PHP (php)

The $mode parameter determines how the fetchAll() returns the next row. The $mode parameter accepts one of the PDO::FETCH_* constants. The most commonly used modes are:

  • PDO::FETCH_BOTH – returns an array indexed by both column name and 0-indexed column number. This is the default.
  • PDO::FETCH_ASSOC – returns an array indexed by column name
  • PDO::FETCH_CLASS – returns a new class instance by mapping the columns to the object’s properties.

The fetchAll() method returns an array that contains all rows of a result set.

If the result set is empty, the fetchAll() method returns an empty array. If the fetchAll() fails to fetch data, it’ll return false .

It’s important to notice that if you have a large result set, the fetchAll() may consume a lot of server memory and possibly network resources. To avoid this, you should execute a query that retrieves only necessary data from the database server.

Using the PHP fetchAll() method with the query() method

If a query doesn’t accept a parameter, you can fetch all rows from the result set as follows:

  • First, execute the query by calling the query() method of the PDO object.
  • Then, fetch all rows from the result set into an array using the fetchAll() method.

The following example illustrates how to use the fetchAll() method to select all rows from the publishers table:

 // connect to the database to get the PDO instance $pdo = require 'connect.php'; $sql = 'SELECT publisher_id, name FROM publishers'; // execute a query $statement = $pdo->query($sql); // fetch all rows $publishers = $statement->fetchAll(PDO::FETCH_ASSOC); // display the publisher name foreach ($publishers as $publisher) < echo $publisher['name'] . '
'
; >
Code language: PHP (php)
1.McGraw-Hill Education 2.Penguin/Random House 3.Hachette Book Group 4.Harper Collins 5.Simon and SchusterCode language: plaintext (plaintext)
$pdo = require 'connect.php';Code language: PHP (php)

Second, execute a query that selects the publisher_id and name from the publishers table:

$sql = 'SELECT publisher_id, name FROM publishers'; $statement = $pdo->query($sql);Code language: PHP (php)

Third, fetch all rows from the result set into an array:

// display the publishers foreach ($publishers as $publisher) < echo $publisher['name'] . '
'
; >
Code language: PHP (php)

Using the fetchAll() method with a prepared statement

If a query accepts one or more parameters, you can:

  • First, execute a prepared statement.
  • Second, fetch all rows from the result set into an array using the fetchAll() method.

The following example shows how to use fetchAll() to fetch all publishers with the id greater than 2:

 // connect to the database to get the PDO instance $pdo = require 'connect.php'; $sql = 'SELECT publisher_id, name FROM publishers WHERE publisher_id > :publisher_id'; // execute a query $statement = $pdo->prepare($sql); $statement->execute([ ':publisher_id' => 2 ]); // fetch all rows $publishers = $statement->fetchAll(PDO::FETCH_ASSOC); // display the publishers foreach ($publishers as $publisher) < echo $publisher['publisher_id'] . '.' . $publisher['name'] . '
'
; >
Code language: PHP (php)
3.Hachette Book Group 4.Harper Collins 5.Simon and SchusterCode language: plaintext (plaintext)

Summary

  • Use the fetchAll() method to fetch a row from the result set associated with a PDOStatement object.

Источник

PDO::query

PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.

For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO::prepare() and issue the statement with multiple calls to PDOStatement::execute() .

If you do not fetch all of the data in a result set before issuing your next call to PDO::query() , your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query() .

Note:

If the query contains placeholders, the statement must be prepared and executed separately using PDO::prepare() and PDOStatement::execute() methods.

Parameters

The SQL statement to prepare and execute.

If the SQL contains placeholders, PDO::prepare() and PDOStatement::execute() must be used instead. Alternatively, the SQL can be prepared manually before calling PDO::query() , with the data properly formatted using PDO::quote() if the driver supports it.

The default fetch mode for the returned PDOStatement . It must be one of the PDO::FETCH_* constants.

If this argument is passed to the function, the remaining arguments will be treated as though PDOStatement::setFetchMode() was called on the resultant statement object. The subsequent arguments vary depending on the selected fetch mode.

Return Values

Returns a PDOStatement object or false on failure.

Errors/Exceptions

Emits an error with level E_WARNING if the attribute PDO::ATTR_ERRMODE is set to PDO::ERRMODE_WARNING .

Throws a PDOException if the attribute PDO::ATTR_ERRMODE is set to PDO::ERRMODE_EXCEPTION .

Examples

Example #1 SQL with no placeholders can be executed using PDO::query()

$sql = ‘SELECT name, color, calories FROM fruit ORDER BY name’ ;
foreach ( $conn -> query ( $sql ) as $row ) print $row [ ‘name’ ] . «\t» ;
print $row [ ‘color’ ] . «\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

See Also

  • PDO::exec() — Execute an SQL statement and return the number of affected rows
  • PDO::prepare() — Prepares a statement for execution and returns a statement object
  • PDOStatement::execute() — Executes a prepared statement

Источник

Оцените статью