Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting MySQL results as PHP array

Tags:

arrays

php

mysql

mysql table:

+-------------------+----------------+
| config_name       |  config_value  |
+-------------------+----------------+
| allow_autologin   |       1        |
| allow_md5         |       0        |
+-------------------+----------------+

current php codes:

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}
print_r($rows);

current result:

Array
(
    [0] => Array
        (
            [config_name] => allow_autologin
            [config_value] => 1
        )

    [1] => Array
        (
            [config_name] => allow_md5
            [config_value] => 0
        )

)

I want to get the result like that:

Array(allow_autologin => 1, allow_md5 => 0)
like image 458
bee gees Avatar asked Mar 10 '26 17:03

bee gees


2 Answers

just add to your results like so:

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[$r['config_name']] = $r['config_value'];
}
print_r($rows);
like image 97
Matt Ellen Avatar answered Mar 13 '26 09:03

Matt Ellen


while($r = mysql_fetch_assoc($sth)) {
    $rows[] = array($r['config_name'] => $r['config_value']);
}
like image 40
jasonbar Avatar answered Mar 13 '26 07:03

jasonbar