note 112924 added to mysqli-result.fetch-assoc
| From: | Miller | Date: | Wed, 07 Aug 2013 17:26:30 +0000 |
| Subject: | note 112924 added to mysqli-result.fetch-assoc | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195904@lists.php.net to get a copy of this message | ||
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.
<?php
$sql = new MySQLi($host, $username, $password, $database);
$result = $sql->query("SELECT * FROM
$table;");
for ($set = array (); $row = $result->fetch_assoc(); $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:
<?php
$sql = new MySQLi($host, $username, $password, $database);
$result = $sql->query("SELECT field2 FROM $table;");
for ($set = array (); $row = $result->fetch_assoc(); $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):
<?php
$sql = new MySQLi($host, $username, $password, $database);
$result = $sql->query("SELECT * FROM $table;");
for ($set = array (); $row = $result->fetch_assoc(); $set[array_shift($row)] = $row);
print_r($set);
?>
Outputs:
Array
(
[1] => Array
(
[field2] => a
[field3] => b
),
[2] => Array
(
[field2] => c
[field3] => d
)
)
----
Server IP: 69.147.83.199
Probable Submitter: 68.14.223.28
----
Manual Page -- http://php.net/manual/en/mysqli-result.fetch-assoc.php
Edit -- https://master.php.net/note/edit/112924
Del: integrated -- https://master.php.net/note/delete/112924/integrated
Del: useless -- https://master.php.net/note/delete/112924/useless
Del: bad code -- https://master.php.net/note/delete/112924/bad+code
Del: spam -- https://master.php.net/note/delete/112924/spam
Del: non-english -- https://master.php.net/note/delete/112924/non-english
Del: in docs -- https://master.php.net/note/delete/112924/in+docs
Del: other reasons-- https://master.php.net/note/delete/112924
Reject -- https://master.php.net/note/reject/112924
Search -- https://master.php.net/manage/user-notes.php