clandmeter Posted January 25, 2008 Share Posted January 25, 2008 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 Quote Link to comment https://forums.phpfreaks.com/topic/87734-sql-table-to-array/ Share on other sites More sharing options...
rajivgonsalves Posted January 25, 2008 Share Posted January 25, 2008 you must of written some code ? Quote Link to comment https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448741 Share on other sites More sharing options...
clandmeter Posted January 25, 2008 Author Share Posted January 25, 2008 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 Quote Link to comment https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448751 Share on other sites More sharing options...
rajivgonsalves Posted January 25, 2008 Share Posted January 25, 2008 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 Quote Link to comment https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448753 Share on other sites More sharing options...
clandmeter Posted January 25, 2008 Author Share Posted January 25, 2008 That seems to work nicely . Thank you! Didn't know i could do it this way with arrays. Carlo Quote Link to comment https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448764 Share on other sites More sharing options...
rajivgonsalves Posted January 25, 2008 Share Posted January 25, 2008 you can check out http://php.net/array there are fine examples out there Quote Link to comment https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448769 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.