Remediëringsoefening

pg_fetch_assoc

pg_fetch_assoc() возвращает ассоциативный массив, содержащий записи из строки результата запроса.

Результат выполнения pg_fetch_assoc() тот же, что и у pg_fetch_array() с параметром PGSQL_ASSOC . Функция возвращает только ассоциативный массив. Если нужен численно-индексированный массив, используйте функцию pg_fetch_row() .

Замечание: Эта функция устанавливает NULL-поля в значение null PHP.

pg_fetch_assoc() не намного медленней и значительно проще в использовании, чем pg_fetch_row() .

Список параметров

Экземпляр PgSql\Result , возвращаемый функциями pg_query() , pg_query_params() или pg_execute() (среди прочего).

Номер выбираемой из результата запроса строки. Нумерация начинается с нуля. Если аргумент опущен или равен null , берётся следующая по очереди строка.

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

Ассоциативный массив, индексированный именами полей выборки. Значения массива представляются в виде текстовых строк. Значения NULL базы данных преобразуются в PHP null .

false , если row превышает число строк в результате запроса, когда строк в результате не осталось, и при прочих ошибках.

Список изменений

Примеры

Пример #1 Пример использования pg_fetch_assoc()

$conn = pg_connect ( «dbname=publisher» );
if (! $conn ) echo «Произошла ошибка.\n» ;
exit;
>

$result = pg_query ( $conn , «SELECT id, author, email FROM authors» );
if (! $result ) echo «Произошла ошибка.\n» ;
exit;
>

while ( $row = pg_fetch_assoc ( $result )) echo $row [ ‘id’ ];
echo $row [ ‘author’ ];
echo $row [ ’email’ ];
>
?>

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

  • pg_fetch_row() — Выбирает строку результата запроса и помещает данные в массив
  • pg_fetch_array() — Возвращает строку результата в виде массива
  • pg_fetch_object() — Выбирает строку результата запроса и возвращает данные в виде объекта
  • pg_fetch_result() — Возвращает запись из результата запроса

User Contributed Notes 17 notes

Note that all pg_fetch_* function ignoring the original type of the data and always return strings. (for numbers too)

PostgreSQL boolean values set to TRUE are returned as the string «t»

PostgreSQL boolean values set to FALSE are returned as the string «f»

If you are moving between different versions of PHP, this might be handy:

if (!function_exists(‘pg_fetch_assoc’)) function pg_fetch_assoc ($result)
return @pg_fetch_array($result, NULL, PGSQL_ASSOC);
>
>

Beware! If your query returns multiple columns with the same names, only the right-most one will be contained in the result array. This can cause problems if you are using a combination of joins:

For example:
// Let’s say that ‘pkey’ is the primary-key colum for tables a and b (primary keys are never null)
$res = pg_query ( «Select a.pkey, b.* FROM a LEFT JOIN b using (pkey)» );
$data = pg_fetch_assoc ( $res );
var_dump ( $data [ ‘pkey’ ]) // Is actually b.pkey, may be NULL!
?>

Both tables contain a column named ‘pkey’. Now table ‘b’ is on the optional side of a LEFT JOIN, so b.pkey (implicitly included via ‘b.*’) may be NULL.

The problem arises when you use pg_fetch_assoc(), there are two columns named ‘pkey’ but the result array can only contain one value per key — in this case it will pick the one from table B instead of the one from table A, and since B is on the optional side of the left-join, $data[‘pkey’] may be NULL. So if you’re expecting to retrieve the column from table A, you need to use a different pg_fetch() or rewrite your query to avoid ambiguity.

Converts ‘t’ and ‘f’ to PHP Boolean

while ( $row = pg_fetch_assoc( $result ) )
fixBooleans($result, $row);

function fixBooleans($result, &$row)

for ($fld_i = 0; $fld_i < pg_num_fields($result); $fld_i++)
$fld_name = pg_field_name($result, $fld_i);

if( pg_field_type($result, $fld_i) == ‘bool’ )
if( $row[ $fld_name ] == ‘t’ )
$row[ $fld_name ] = true;
>
elseif($row[ $fld_name ] == ‘f’)
$row[ $fld_name ] = false;
>
>
>


// keuzemenu met alle leerkrachten
function leerkrachten ( $aName ) include( «includes/connect.php» );

>
// keuzemenu met alle vakken
function vakken ( $aID ) include( «includes/connect.php» );
$SelectVakkenQuery = «SELECT * FROM vakken» ;
$SelectVakkenResult = $mysqli -> query ( $SelectVakkenQuery );
$Choice = » $aID ‘ onchange=waarde()>» ;

while( $rij2 = $SelectVakkenResult -> fetch_assoc ()) $VakID = $rij2 [ ‘vakid’ ];
$Vaknaam = $rij2 [ ‘voluit’ ];
$Choice .= »» ;
>
$Choice .= «» ;
return $Choice ;
>
?>

include( «includes/connect.php» );
// aanmaken van keuzemenus

// eerste keuzemenu
echo vakken ( «optVakken» ). «

» ;

// tweede keuzemenu
if(!isset( $_POST [ ‘txthidden’ ])) $SelectLeerkrachtenQuery = «SELECT * FROM leerkrachten» ;
$SelectLeerkrachtResult = $mysqli -> query ( $SelectLeerkrachtenQuery );

$Choice = «

» ;
echo $Choice ;
>else $vakid = $_POST [ ‘txthidden’ ];
$SelectLeerkrachtenQuery = «SELECT * FROM leerkrachten JOIN leerkrachtpervak ON leerkrachten.leerkrachtid = leerkrachtpervak.leerkrachtid WHERE vakid = ‘ $vakid ‘» ;
$SelectLeerkrachtResult = $mysqli -> query ( $SelectLeerkrachtenQuery );
$Choice = «

» ;
echo $Choice ;
>
// onzichtbaar textbox voor JS
echo » » ;
$mysqli -> close ();
?>

Here is much powerful pg_parse_array() variant, based on FSM: for any dimension Postgres arrays (its string representation must be well-formed), with quotation rules checks, complexity O(N), where N is a length of string representation of Postgres array:

define ( ‘STATE_BEGIN’ , 1 );
define ( ‘STATE_INARRAY’ , 2 );
define ( ‘STATE_OUTARRAY’ , 3 );
define ( ‘STATE_INSLASH’ , 4 );
define ( ‘STATE_INQUOTES’ , 5 );

function pg_parse_array ( $value ) $resultArray = $indexArray = array(); $level = $index = 0 ;
$ptr = & $resultArray ;
for( $i = 0 ; $i < strlen ( $value ); $i ++)switch( $level ) case 1 :
if( $index > 0 ) $ptr = & $ptr [ sizeof ( $ptr )];
>
$indexArray [++ $index ] = & $ptr ;
break;
case — 1 :
$ptr = & $indexArray [— $index ];
break;
>
$level = processFSM ( $value < $i >, $ptr );
>
return $resultArray ;
>

case $state !== STATE_BEGIN :
$state = $state === STATE_INSLASH ? STATE_INQUOTES : $state ;
isset( $result [ $index ]) or $result [ $index ] = » ;
$result [ $index ] .= $chr ;
break;
>
return $level ;
>

Be aware that if one of your result fields is an array, it will be output as a string using the general format of ‘‘ in accordance with postgres’s behavior with SQL arrays.
http://www.postgresql.org/docs/8.4/static/arrays.html#ARRAYS-IO

So, here is a function to convert simple (one-dimensional) SQL arrays to PHP arrays:

function pg_parse_array ( $field )
/*
* Converts a simple SQL array field to its PHP equivalent. e.g:
*
* —> Array(null);
* —> Array(«null»);
* —> Array(«foo», «bar»);
* —> Array(«foo,bar»);
* —> Array(‘Hello «World»‘);
*
*/
// NULL fields are always NULL
if (! is_string ( $field )) return $field ;

// Check for curly braces which may indicate an SQL array field
if ( $field [ 0 ] != » ) return $field ;
$field = trim ( substr ( $field , 1 , — 1 ));

// Break up the string into the following:
// — quoted text that MAY have special chars escaped by a backslash
// — unquoted text that may NOT have special chars
$search = ‘/(«)?+((?(1)(?:\\\\.|[^»])*|[^,]+))(?(1)\\1)/’ ;
preg_match_all ( $search , $field , $matches , PREG_SET_ORDER );

foreach( $matches as $value )
if ( $value [ 1 ])
// Quoted element, with backslash used to escape chars
$array [] = preg_replace ( ‘#\\\\(.)#’ , ‘$1’ , $value [ 2 ]);
>
else
// Unquoted element
$value [ 2 ] = trim ( $value [ 2 ]);
if ( strtolower ( $value [ 2 ]) == ‘null’ ) $array [] = null ; // NULL
else $array [] = $value [ 2 ];
>
>
return $array ;
>

// Some tests to demonstrate this function
var_export ( pg_parse_array ( » ); // Output is Array(null);
var_export ( pg_parse_array ( » ); // Output is Array(‘foo’, ‘bar’);
var_export ( pg_parse_array ( » ); // Output is Array(‘null’);

Источник

pg_fetch_array

pg_fetch_array() возвращает массив, соответствующий выбранной строке (записи).

pg_fetch_array() расширенная версия функции pg_fetch_row() . Эта функция способна сохранить данные не только с цифровыми индексами, но и с ассоциативными (имя поля). По умолчанию хранит и те и другие.

Замечание: Эта функция устанавливает NULL-поля в значение null PHP.

pg_fetch_array() выполняется незначительно медленнее чем pg_fetch_row() , но значительно проще в использовании.

Список параметров

Экземпляр PgSql\Result , возвращаемый функциями pg_query() , pg_query_params() или pg_execute() (среди прочего).

Номер строки в result для выборки. Строки пронумерованы с 0 по возрастанию. Если параметр опущен или передан null будет выбрана следующая строка.

Необязательный параметр, управляющий тем, как индексируется возвращаемый массив ( array ). Параметр mode является константой и может принимать следующие значения: PGSQL_ASSOC , PGSQL_NUM и PGSQL_BOTH . При использовании PGSQL_NUM функция возвращает массив с числовыми индексами, при использовании PGSQL_ASSOC она вернёт только ассоциативные индексы, а PGSQL_BOTH вернёт как числовые, так и ассоциативные индексы.

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

Массив ( array ) с числовыми индексами (начиная с 0), либо ассоциативными (по имени поля), либо с обеими типами индексов. Каждое значение в массиве ( array ) представлено как строка ( string ). Значение NULL возвращается как null .

Функция возвращает false , если row выходит за рамки количества строк в выборке, или отсутствия строк, или в случае любой другой ошибки. Выборка из результата запроса, отличного от SELECT, также вернёт false .

Список изменений

Примеры

Пример #1 Пример использования pg_fetch_array()

$conn = pg_pconnect ( «dbname=publisher» );
if (! $conn ) echo «Произошла ошибка.\n» ;
exit;
>

$result = pg_query ( $conn , «SELECT author, email FROM authors» );
if (! $result ) echo «Произошла ошибка.\n» ;
exit;
>

$arr = pg_fetch_array ( $result , 0 , PGSQL_NUM );
echo $arr [ 0 ] . » echo $arr [ 1 ] . »

// Параметр row необязателен,
// для передечи result_type вместо row можно передать NULL.
// Успешные вызовы pg_fetch_array вернут следующий ряд.

$arr = pg_fetch_array ( $result , NULL , PGSQL_ASSOC );
echo $arr [ «author» ] . » echo $arr [ «email» ] . »

$arr = pg_fetch_array ( $result );
echo $arr [ «author» ] . » echo $arr [ 1 ] . »

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

  • pg_fetch_row() — Выбирает строку результата запроса и помещает данные в массив
  • pg_fetch_object() — Выбирает строку результата запроса и возвращает данные в виде объекта
  • pg_fetch_result() — Возвращает запись из результата запроса

Источник

Working with PostgreSQL Arrays in PHP

Working with PostgreSQL Arrays in PHP

I recently had to do some work with PostgreSQL arrays in a PHP app. My first question: how do I manage arrays as parameterized values in a query?

Turns out there are two ways forward:

Array Literals

These appear in the Postgres documentation as curly brace surrounded, comma delimited lists: .

A literal like this can be put into a parameter:

/** @var PDO $conn */ $stm = $conn->prepare('INSERT INTO array_table (array_col) VALUES (:v)'); $stm->bindValue(':v', ''); $stm->execute();

This works okay, but if any of the values of an array have a curly braces or quotes (or any other character that needs escaping) things can get weird. By weird I meant the PHP code will have to handle escaping itself. Which sounds like a recipe for distaster.

Array Constructors

In addition to array literals, Postgres offers an Array constructor syntax: ARRAY[1, 2, 3] .

Each one of those values in the ARRAY constructor can be parameterized:

/** @var PDO $conn */ $stm = $conn->prepare('INSERT INTO array_table (array_col) VALUES (ARRAY[:a, :b, :c]::integer[])'); $stm->bindValue(':a', 1, PDO::PARAM_INT); $stm->bindValue(':b', 2, PDO::PARAM_INT); $stm->bindValue(':c', 3, PDO::PARAM_INT); $stm->execute();

Using the array constructor syntax means escaping issues are no longer a concern. It also means that we can bind correct parameter types. This solution is more verbose, however. Non-text data types will require a ::type[] cast as seen in the example above.

Источник

Читайте также:  Php unset all cookie
Оцените статью