简体   繁体   中英

SQL Results as PHP Array

I am trying to solve this. Maybe this is absolutly incorrect, I need some help.

I have a table like this:

INSERT INTO `municipios` (`id`, `provincia`, `municipio`) VALUES (1, 1, 'Alegría-Dulantzi'), (2, 1, 'Amurrio'), (3, 1, 'Añana'), (4, 1, 'Aramaio'), (5, 1, 'Armiñón'),

And this is my handler:

    $query = "SELECT * FROM municipios WHERE provincia='1'";
$result = mysql_query($query);      
while ($row = mysql_fetch_array($result)) {                 
    $groups = array(
    $row{'id'} => array(
        'name' => $row{'municipio'},
        'description' => 'Agrupación electoral de ' . $row{'municipio'},
        'status' => 'public',
        'enable_forum' => 1,
        ),
        );
}

With this I got just the last result. I have tried another options, but doesn´t work.

Something like this should solve your issue:

$groups[] = array(
     $row['id'] => array(
        'name' => $row['municipio'],
        'description' => 'Agrupación electoral de ' . $row['municipio'],
       'status' => 'public',
       'enable_forum' => 1,
     ),
  );

However, may i suggest your use PDO. There is a pretty good article http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ that should get you going in the right direction.

Is this an issue with the way you're appending the groups array? I think your overwriting the array every time u set a value. Try using array_push() to append to groups.

Let us know of that helps!

array_push() http://php.net/manual/en/function.array-push.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM