Jump to content

Getting contents of DB table into array


Riari

Recommended Posts

Hello all,

 

I'm sure something like this has been brought up before but I think it's quite a unique problem and I didn't get anywhere searching... so here's my first post. Yay.  :)

 

Right, so, basically I have a database table that looks like this:

 

+----------+-------+
| name     | value |
+----------+-------+
| settingA | true  |
| settingB | false |
| settingC | false |
+----------+-------+

 

And I have been racking my brains trying to figure out how to get that data into an array formatted like so:

 

Array
(
[settingA] => true
[settingB] => false
[settingC] => false
)

 

The best I have been able to do, using nested foreach() statements, is this:

 

Array
(
    [0] => Array
        (
            [name] => settingA
            [value] => true
        )

    [1] => Array
        (
            [name] => settingB
            [value] => false
        )

    [2] => Array
        (
            [name] => settingC
            [value] => false
        )

)

 

...which is not very practical, or at least it isn't for what I want to do. Any ideas on what the best method might be for achieving this? I am using ADOdb Lite but even an example using PHP's native MySQL functions could help me figure out what to do.

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/234770-getting-contents-of-db-table-into-array/
Share on other sites

  while($row = mysql_fetch_assoc($query)){
   $settings[] = $row['setting'];
   $values[]   = $row['value'];
  }

  $settings = array_combine($settings,$values);
  echo '<pre>';
  print_r($settings);

 

Try the above, tell me how it goes :)

 

Regards, PaulRyan.

@PaulRyan, that works! I had to spend a few minutes figuring out an equivalent to mysql_fetch_assoc() in ADOdb, but I got there in the end.

 

For reference (in case anyone else with the exact same problem stumbles across this thread), this is the gist of the code I ended up with:

 

        $query = $DB->Execute("SELECT * FROM `config`");
        $result = $query->getArray();

        foreach($result as $row) {
            $settings[] = $row['name'];
            $values[]   = $row['value'];
        }

        $config = array_combine($settings, $values);

 

Thanks for your help, guys. :)

Save the extra steps:

 

        $query = $DB->Execute("SELECT * FROM `config`");
        $result = $query->getArray();
        $config = array();
        foreach($result as $row) {
            $config[$row['name']] = $row['value'];
        }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.