tags:

views:

42

answers:

5

Hello,

I got a database with 2 fields (amount and name). I want to get all data from the database (40 rows) and create an associated array out of it like this.

$arr = array("amount" => "12", "name" => "John");

How is this done dynamically in PHP? I am stuck.

A: 

Check out mysql_fetch_assoc if you want to fetch database rows as an associative array (the documentation comes with a good example, too).

Daff
+1  A: 

Well, if you run your query, e.g.

$result = mysql_query('SELECT amount, name FROM table');

you can loop over the result like that:

$values = array();

while(($row = mysql_fetch_assoc($result))) {
   $values[] = $row;//$row will be like array("amount" => "12", "name" => "John")
}

and you will have an array of arrays.

Felix Kling
A: 

If you are using standard MySQL functions, use mysql_fetch_assoc, the fetchAll method for PDO, and fetch_assoc for MySQLi.

Tim Cooper
+1  A: 

If you're using the mysql_* function, you can do the following to get one row at a time:

$res = mysql_query("SELECT amount, name FROM mytable");
while ($row = mysql_fetch_assoc($res)) {
    var_export($row); // outputs array ( 'amount' => '12', 'name' => 'John', )
}

To get all rows in a single array:

$customers = array();
$res = mysql_query("SELECT amount, name FROM customers");
while ($row = mysql_fetch_assoc($res)) {
    $customers[] = $row;
}
webbiedave
A: 
$data = $pdo->query('SELECT amount, name FROM ...')->fetchAll(PDO::FETCH_ASSOC);

That's it in PDO. And if you're not using PDO, well, that's your problem then...

nikic