Title: PHP array question Post by: P4man on February 25, 2012, 10:32:34 AM Im struggling with PHP to get data from a mysql db and put it in to PHP arrays in a way thats actually easy to use.
Assume I have a table "miners'" with the following fields: ip (also primary key) name status location ... I want to fetch this from mysql, put in an array and then loop through all miners, in this example just to display the ip and names. The best Ive come up with is this: Code: $query = "SELECT * FROM miners"; I does work, but its such a kludge. Im sure there is a better way, but I just dont see it. Any help appreciated. Title: Re: PHP array question Post by: legitnick on February 25, 2012, 11:21:12 AM Don't use PHP.
Title: Re: PHP array question Post by: P4man on February 25, 2012, 11:27:58 AM Im contemplating sending you 5BTC for this extremely useful post :)
Title: Re: PHP array question Post by: Bitsky on February 25, 2012, 11:44:15 AM Why don't you use the returned arrays while fetching them from Mysql?
Code: $id=mysql_query('SELECT * FROM miners'); Or use PDO, it has a fetchAll statement (and prepare/execute is nicer too) Title: Re: PHP array question Post by: P4man on February 25, 2012, 12:12:22 PM Why don't you use the returned arrays while fetching them from Mysql? TBH, because my code is already working with arrays that are initialized on startup, so hardcoded. Now I just want to fetch the data from a db without rewriting everything. Looks like I may have to. Title: Re: PHP array question Post by: Bitsky on February 25, 2012, 12:39:12 PM You could always write a function if you need this more than once.
Code: function mysql_fetch_all($q) { Of course this could be made prettier, but bascially it's working. Title: Re: PHP array question Post by: neo_rage on February 25, 2012, 01:09:32 PM Well, if so:
Quote I want to fetch this from mysql, put in an array and then loop through all miners, in this example just to display the ip and names. Code: $query = "SELECT * FROM miners"; well, if you 'nt need to put all fetched rows in array, you can do smth like that: Code: $query = "SELECT * FROM miners"; no such kludge, by the way. Title: Re: PHP array question Post by: Bitsky on February 25, 2012, 01:14:18 PM Something that should be pointed out: using * in queries is generally a bad idea. Fetch the columns you need, not everything.
(Yeah I know I've been lazy in my examples too) Title: Re: PHP array question Post by: legitnick on February 25, 2012, 01:49:13 PM Im contemplating sending you 5BTC for this extremely useful post :) Give Django a try and once you get comfortable with it you'll realize how shitty php is in general.. |