Fetch array function in php

PHP mysqli_fetch_array() Function

A PHP result object (of the class mysqli_result) represents the MySQL result, returned by the SELECT or, DESCRIBE or, EXPLAIN queries.

The mysqli_fetch_array() function accepts a result object as a parameter and, retrieves the contents of current row in the given result object, and returns them as an associative or, numeric array.

Syntax

mysqli_fetch_array($result, [$type]);

Parameters

This is an identifier representing a result object.

This is an integer value specifying the type of the returned array. The value of this cane be one of the following −

Return Values

The PHP mysqli_fetch_array() function returns an array (associative or, numeric) which holds the current row of the result object. This function returns NULL if there are no more rows.

PHP Version

This function was first introduced in PHP Version 5 and works works in all the later versions.

Example

Following example demonstrates the usage of the mysqli_fetch_array() function (in procedural style) −

 //Closing the statement mysqli_free_result($res); //Closing the connection mysqli_close($con); ?>

This will produce following result −

Table Created. Record Inserted. ID: 1 First_Name: Sikhar Last_Name: Dhawan Place_Of_Birth: Delhi Country: India ID: 2 First_Name: Jonathan Last_Name: Trott Place_Of_Birth: CapeTown Country: SouthAfrica ID: 3 First_Name: Kumara Last_Name: Sangakkara Place_Of_Birth: Matale Country: Srilanka

Example

In object oriented style the syntax of this function is $result->fetch_array(); Following is the example of this function in object oriented style $minus;

 query("CREATE TABLE Test(Name VARCHAR(255), Age INT)"); $con -> query("insert into Test values('Raju', 25),('Rahman', 30),('Sarmista', 27)"); print("Table Created. \n"); $stmt = $con -> prepare( "SELECT * FROM Test WHERE Name in(?, ?)"); $stmt -> bind_param("ss", $name1, $name2); $name1 = 'Raju'; $name2 = 'Rahman'; //Executing the statement $stmt->execute(); //Retrieving the result $result = $stmt->get_result(); //Fetching all the rows as arrays while($row = $result->fetch_array(MYSQLI_ASSOC)) < print("Name: ".$row["Name"]."\n"); print("Age: ".$row["Age"]."\n"); >//Closing the statement $stmt->close(); //Closing the connection $con->close(); ?>

This will produce following result −

Table Created. Name: Raju Age: 25 Name: Rahman Age: 30

Example

You can also retrieve the contents of a result row as a numeric array −

 //Closing the statement mysqli_free_result($res); //Closing the connection mysqli_close($con); ?>

This will produce following result −

Table Created. Record Inserted. ID: 1 First_Name: Sikhar Last_Name: Dhawan Place_Of_Birth: Delhi Country: India ID: 2 First_Name: Jonathan Last_Name: Trott Place_Of_Birth: CapeTown Country: SouthAfrica ID: 3 First_Name: Kumara Last_Name: Sangakkara Place_Of_Birth: Matale Country: Srilanka

Источник

Читайте также:  Moocbeliro ru moodle enrol index php

mysql_fetch_array

Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:

Описание

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

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

Обрабатываемый результат запроса. Этот результат может быть получен с помощью функции mysql_query() .

Тип возвращаемого массива. Является константой и может принимать следующие значения: MYSQL_ASSOC , MYSQL_NUM и MYSQL_BOTH .

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

Возвращает массив строк, соответствующих обработанному ряду результата запроса, или FALSE , если рядов больше нет. Тип возвращаемого массива зависит от значения параметра result_type . При использовании MYSQL_BOTH (по умолчанию), вы получите массив, состоящий как из ассоциативных индексов, так и из численных. MYSQL_ASSOC вернёт только ассоциативные индексы (аналогично функции mysql_fetch_assoc() ), а MYSQL_NUM — только численные (аналогично функции mysql_fetch_row() ).

Если несколько колонок в результате будут иметь одинаковые названия, то будет возвращена последняя колонка. Чтобы получить доступ к другим колонкам с тем же именем, используйте численные индексы массива или псевдонимы в запросе. В случае псевдонимов используйте именно их — вы не сможете использовать настоящие имена колонок.

Примеры

Пример #1 Запрос с применением псевдонимов для дублирующихся имен колонок

SELECT table1.field AS foo, table2.field AS bar FROM table1, table2

Пример #2 mysql_fetch_array() с MYSQL_NUM

mysql_connect ( «localhost» , «mysql_user» , «mysql_password» ) or
die( «Ошибка соединения: » . mysql_error ());
mysql_select_db ( «mydb» );

$result = mysql_query ( «SELECT id, name FROM mytable» );

while ( $row = mysql_fetch_array ( $result , MYSQL_NUM )) printf ( «ID: %s Имя: %s» , $row [ 0 ], $row [ 1 ]);
>

Пример #3 mysql_fetch_array() с MYSQL_ASSOC

mysql_connect ( «localhost» , «mysql_user» , «mysql_password» ) or
die( «Ошибка соединения: » . mysql_error ());
mysql_select_db ( «mydb» );

$result = mysql_query ( «SELECT id, name FROM mytable» );

Читайте также:  Установка bitrix bitrixsetup php

while ( $row = mysql_fetch_array ( $result , MYSQL_ASSOC )) printf ( «ID: %s Имя: %s» , $row [ «id» ], $row [ «name» ]);
>

Пример #4 mysql_fetch_array() с MYSQL_BOTH

mysql_connect ( «localhost» , «mysql_user» , «mysql_password» ) or
die( «Ошибка соединения: » . mysql_error ());
mysql_select_db ( «mydb» );

$result = mysql_query ( «SELECT id, name FROM mytable» );

while ( $row = mysql_fetch_array ( $result , MYSQL_BOTH )) printf ( «ID: %s Имя: %s» , $row [ 0 ], $row [ «name» ]);
>

Примечания

Замечание: Производительность

Важно заметить, что mysql_fetch_array() работает незначительно медленнее, чем mysql_fetch_row() , в то же время предоставляя намного более удобный доступ к данным.

Замечание: Имена полей, возвращаемые этой функцией являются регистро-зависимыми.

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

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

  • mysql_fetch_row() — Обрабатывает ряд результата запроса и возвращает массив с числовыми индексами
  • mysql_fetch_assoc() — Возвращает ряд результата запроса в качестве ассоциативного массива
  • mysql_data_seek() — Перемещает внутренний указатель в результате запроса
  • mysql_query() — Посылает запрос MySQL

Источник

PHP mysqli_fetch_array

In this tutorial, we will learn how to use the mysqli_fetch_array function in PHP. This function allows us to retrieve rows from a MySQL database and store them as a PHP array. The function enables you to store the values as an associative array, a numerical array, or a combination of both. You can then manipulate the array as usual. Let us dive in.

Function Syntax

The following snippet shows the procedural syntax for the mysqli_fetch_array function:

mysqli_fetch_array(mysqli_result $result, int $mode = MYSQLI_BOTH): array|null|false

The function parameters are as shown:

  1. result – this parameter allows you to specify the mysql_result object returned by the mysqli_query(), mysqli_store_result(), mysqli_stmt_get_result(), or mysqli_use_result() functions.
  2. mode – the mode parameter defines the type of array used to store the resulting values. Accepted values include:
    1. MYSQLI_ASSOC – associative array.
    2. MYSQLI_NUM – numerical array.
    3. MYSQLI_BOTH – a combination of the associative and numerical array.

    The function will then return the array with the fetched rows. If there are no fetched rows, the function returns null or false on failure.

    Example Usage

    Let us discuss an example of using the mysqli_fetch_array() function. Start by creating a sample database, table, and data as shown in the query below:

    CREATE DATABASE src;
    USE src;
    DROP TABLE IF EXISTS stack_mapping;
    CREATE TABLE stack_mapping (
    id INT AUTO_INCREMENT PRIMARY KEY ,
    server_name VARCHAR ( 50 ) NOT NULL ,
    address VARCHAR ( 100 ) NOT NULL ,
    installed_version VARCHAR ( 50 ) ,
    tool_id INT
    ) ;
    INSERT INTO stack_mapping ( server_name , address , installed_version , tool_id )
    VALUES ( ‘SQL Server’ , ‘localhost:1433’ , ‘15.0’ , 1 ) ,
    ( ‘Elasticsearch’ , ‘localhost:9200’ , ‘8.4’ , 2 ) ,
    ( ‘Redis’ , ‘localhost:6379’ , ‘6.0’ , 3 ) ,
    ( ‘PostgreSQL’ , ‘localhost:5432’ , ‘14.5’ , 4 ) ,
    ( ‘MySQL’ , ‘localhost:3306’ , ‘8.0’ , NULL ) ;

    The resulting table is as shown:

    The following example shows how to use PHP mysqli_fetch_array function to return the rows from the table above as an array.

    Start by creating a PHP file:

    $query = «SELECT server_name, address FROM stack_mapping» ;
    $result = mysqli_query ( $mysqli , $query ) ;

    while ( $row = mysqli_fetch_array ( $result , MYSQLI_ASSOC ) ) {
    printf ( » %s ( %s ) \n » , $row [ «server_name» ] , $row [ «address» ] ) ;
    }
    mysqli_free_result ( $result ) ;
    ?>

    Finally, run the script with PHP:

    This should return the rows as an associative array, also known as a dictionary in other programming languages.

    NOTE: Note we are accessing the values of the dictionary using the row name (dictionary key).

    An example output is as shown:

    SQL Server (localhost:1433)
    Elasticsearch (localhost:9200)
    Redis (localhost:6379)
    PostgreSQL (localhost:5432)
    MySQL (localhost:3306)

    To return the values as a numerical array, we can use the query:

    $query = «SELECT server_name, address FROM stack_mapping» ;
    $result = mysqli_query ( $mysqli , $query ) ;

    while ( $row = mysqli_fetch_array ( $result , MYSQLI_NUM ) ) {
    printf ( » %s ( %s ) \n » , $row [ 0 ] , $row [ 1 ] ) ;
    }
    mysqli_free_result ( $result ) ;
    ?>

    Similarly, the code above should return the rows as:

    SQL Server (localhost:1433)
    Elasticsearch (localhost:9200)
    Redis (localhost:6379)
    PostgreSQL (localhost:5432)
    MySQL (localhost:3306)

    Finally, to get the results as both associative and numerical arrays.

    $query = «SELECT server_name, address FROM stack_mapping» ;
    $result = mysqli_query ( $mysqli , $query ) ;

    while ( $row = mysqli_fetch_array ( $result , MYSQLI_BOTH ) ) {
    printf ( » %s ( %s ) \n » , $row [ 0 ] , $row [ «address» ] ) ;
    }
    mysqli_free_result ( $result ) ;
    ?>

    Conclusion

    In this article, you learned how to use the mysqli_fetch_array function in PHP to fetch the rows from a database as an array.

    About the author

    John Otieno

    My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

    Источник

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