PHP: Hypertext Preprocessor (original) (raw)
mysqli_result::fetch_assoc
mysqli_fetch_assoc
(PHP 5, PHP 7, PHP 8)
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch the next row of a result set as an associative array
Description
Object-oriented style
If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name,mysqli_fetch_row() may be used to fetch the numerically indexed array, or aliases may be used in the SQL query select list to give columns different names.
Note: Field names returned by this function are case-sensitive.
Note: This function sets NULL fields to the PHP
[null](reserved.constants.php#constant.null)
value.
Return Values
Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set's columns, [null](reserved.constants.php#constant.null)
if there are no more rows in the result set, or [false](reserved.constants.php#constant.false)
on failure.
Examples
Example #1 mysqli_result::fetch_assoc() example
Object-oriented style
`<?php
mysqli_report
(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); mysqli=newmysqli("localhost","myuser","mypassword","world");mysqli = new mysqli("localhost", "my_user", "my_password", "world");mysqli=newmysqli("localhost","myuser","mypassword","world");query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";$result = mysqli−>query(mysqli->query(mysqli−>query(query);/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", row["Name"],row["Name"], row["Name"],row["CountryCode"]);
}`
Procedural style
`<?php
mysqli_report
(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); mysqli=mysqliconnect("localhost","myuser","mypassword","world");mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");mysqli=mysqliconnect("localhost","myuser","mypassword","world");query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";$result = mysqli_query($mysqli, $query);/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf("%s (%s)\n", row["Name"],row["Name"], row["Name"],row["CountryCode"]);
}`
The above examples will output something similar to:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)
Example #2 Comparison of mysqli_result iterator and mysqli_result::fetch_assoc() usage
mysqli_result can be iterated using foreach. The result set will always be iterated from the first row, regardless of the current position.
`<?php
mysqli_report
(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); mysqli=newmysqli("localhost","myuser","mypassword","world");mysqli = new mysqli("localhost", "my_user", "my_password", "world");mysqli=newmysqli("localhost","myuser","mypassword","world");query = 'SELECT Name, CountryCode FROM City ORDER BY ID DESC';// Using iterators result=result = result=mysqli->query($query);
foreach ($result as $row) {
printf("%s (%s)\n", row["Name"],row["Name"], row["Name"],row["CountryCode"]);
}
echo
"\n==================\n";// Not using iterators result=result = result=mysqli->query($query);
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", row["Name"],row["Name"], row["Name"],row["CountryCode"]);
}`
The above example will output something similar to:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)
================== Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA)
See Also
- mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
- mysqli_fetch_column() - Fetch a single column from the next row of a result set
- mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
- mysqli_fetch_object() - Fetch the next row of a result set as an object
- mysqli_query() - Performs a query on the database
- mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result
Found A Problem?
11 years ago
`` I often like to have my results sent elsewhere in the format of an array (although keep in mind that if you just plan on traversing through the array in another part of the script, this extra step is just a waste of time).
This is my one-liner for transforming a mysqli_result set into an array.
sql=newMySQLi(sql = new MySQLi(sql=newMySQLi(host, username,username, username,password, database);database);database);result = sql−>query("SELECT∗FROM‘sql->query("SELECT * FROM `sql−>query("SELECT∗FROM‘table`;");
for ($set = array (); row=row = row=result->fetch_assoc(); set[]=set[] = set[]=row);
print_r($set);
?>
Outputs:
Array
(
[0] => Array
(
[id] => 1
[field2] => a
[field3] => b
),
[1] => Array
(
[id] => 2
[field2] => c
[field3] => d
)
)
I use other variations to adapt to the situation, i.e. if I am selecting only one field:
sql=newMySQLi(sql = new MySQLi(sql=newMySQLi(host, username,username, username,password, database);<spanclass="katex"><spanclass="katex−mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>e</mi><mi>s</mi><mi>u</mi><mi>l</mi><mi>t</mi><mo>=</mo></mrow><annotationencoding="application/x−tex">result=</annotation></semantics></math></span><spanclass="katex−html"aria−hidden="true"><spanclass="base"><spanclass="strut"style="height:0.6944em;"></span><spanclass="mordmathnormal">res</span><spanclass="mordmathnormal">u</span><spanclass="mordmathnormal">lt</span><spanclass="mspace"style="margin−right:0.2778em;"></span><spanclass="mrel">=</span></span></span></span>sql−>query("SELECT‘field2‘FROM‘database); <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>e</mi><mi>s</mi><mi>u</mi><mi>l</mi><mi>t</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">result = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">res</span><span class="mord mathnormal">u</span><span class="mord mathnormal">lt</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>sql->query("SELECT `field2` FROM `database);<spanclass="katex"><spanclass="katex−mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>e</mi><mi>s</mi><mi>u</mi><mi>l</mi><mi>t</mi><mo>=</mo></mrow><annotationencoding="application/x−tex">result=</annotation></semantics></math></span><spanclass="katex−html"aria−hidden="true"><spanclass="base"><spanclass="strut"style="height:0.6944em;"></span><spanclass="mordmathnormal">res</span><spanclass="mordmathnormal">u</span><spanclass="mordmathnormal">lt</span><spanclass="mspace"style="margin−right:0.2778em;"></span><spanclass="mrel">=</span></span></span></span>sql−>query("SELECT‘field2‘FROM‘table`;");
for ($set = array (); row=row = row=result->fetch_assoc(); set[]=set[] = set[]=row['field2']);
print_r($set);
?>
Outputs:
Array
(
[0] => a
[1] => c
)
Or, to make the array associative with the primary index (code assumes primary index is the first field in the table):
sql=newMySQLi(sql = new MySQLi(sql=newMySQLi(host, username,username, username,password, database);<spanclass="katex"><spanclass="katex−mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>e</mi><mi>s</mi><mi>u</mi><mi>l</mi><mi>t</mi><mo>=</mo></mrow><annotationencoding="application/x−tex">result=</annotation></semantics></math></span><spanclass="katex−html"aria−hidden="true"><spanclass="base"><spanclass="strut"style="height:0.6944em;"></span><spanclass="mordmathnormal">res</span><spanclass="mordmathnormal">u</span><spanclass="mordmathnormal">lt</span><spanclass="mspace"style="margin−right:0.2778em;"></span><spanclass="mrel">=</span></span></span></span>sql−>query("SELECT∗FROM‘database); <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>e</mi><mi>s</mi><mi>u</mi><mi>l</mi><mi>t</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">result = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord mathnormal">res</span><span class="mord mathnormal">u</span><span class="mord mathnormal">lt</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>sql->query("SELECT * FROM `database);<spanclass="katex"><spanclass="katex−mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>e</mi><mi>s</mi><mi>u</mi><mi>l</mi><mi>t</mi><mo>=</mo></mrow><annotationencoding="application/x−tex">result=</annotation></semantics></math></span><spanclass="katex−html"aria−hidden="true"><spanclass="base"><spanclass="strut"style="height:0.6944em;"></span><spanclass="mordmathnormal">res</span><spanclass="mordmathnormal">u</span><spanclass="mordmathnormal">lt</span><spanclass="mspace"style="margin−right:0.2778em;"></span><spanclass="mrel">=</span></span></span></span>sql−>query("SELECT∗FROM‘table`;");
for ($set = array (); row=row = row=result->fetch_assoc(); set[arrayshift(set[array_shift(set[arrayshift(row)] = $row);
print_r($set);
?>
Outputs:
Array
(
[1] => Array
(
[field2] => a
[field3] => b
),
[2] => Array
(
[field2] => c
[field3] => d
)
)
``
james dot phx at gmail dot com ¶
13 years ago
`IMPORTANT NOTE:
If you were used to using code like this:
You must change it to this for mysqli:
The former will cause your script to run until max_execution_time is reached.
`
2 years ago
There is a difference between MariaDB and MySQL(>5.4) whether the input parameter (mysqli object) has data or is empty (it comes from a previus query). -MariaDB: you get an exception: Fatal error: Uncaught TypeError: mysqli_fetch_assoc(): Argument #1 ($result) must be of type mysqli_result -MySQL: you can continue, in spite of not having data in the mysqli object.