Jump to content

sql table to array


clandmeter

Recommended Posts

Hi,

 

I have a simple task which i can seem to solve.

 

I have a table in my database like this:

 

id      fruit      color

1      apple    green

2      banana  yellow

.......

 

Now i want to create an array where to key is the id and the value is the fruit.

array(1 => apple, 2 => banana, .....)

 

How would i do this with php/mysql?

 

TIA,

 

Carlo

Link to comment
https://forums.phpfreaks.com/topic/87734-sql-table-to-array/
Share on other sites

you must of written some code ?

 

Not sure if i understand your question.

 

I am trying to create a Drupal cms module in php.

 

This is what i tried but its not correct:

 

<?php 
  $query = ("SELECT * FROM {table}");
  $result = db_query($query);
  while ($row = db_fetch_array($result)) {
    $ptype = array($row[id] => $row[type]);
  }
?>

 

Now everytime it looks it will rewrite the array so in the end it only holds the last row.

What I want is that it holds all the rows in that array so the id's are the keys and the values are the type.

 

Hope this is clearer now.

 

Carlo

 

Link to comment
https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448751
Share on other sites

your code should be

 

<?php 
  $query = ("SELECT * FROM {table}");
  $result = db_query($query);
$ptype = array();
  while ($row = db_fetch_array($result)) {
    $ptype[$row[id]] = $row[type];
  }

print_r($ptype);
?>

 

 

hope its helpful

Link to comment
https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448753
Share on other sites

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.