[thelist] functionitis

Beam sbeam at syxyz.net
Thu Apr 3 11:39:30 CST 2003

> Should I make a
> function to create these two pieces, or should I copy and paste?
> How do you make these kinds of decisions on whether or not to build a
> new function?

A rule of thumb I've heard, and often ignored, is: 2x2 - if it is more than 2 
lines or you are going to use it more than twice, make it reusable

> <tip author="emmajane" type="storing PHP database output">
> If you want to access the database field names in your array use an
> associative array to store rows from your database:
> 	while ($rows = mysql_fetch_array($mysql_query)) {
> 		$results[$rows["id"]]["column1"] = $rows["column1"];
> 		$results[$rows["id"]]["column2"] = $rows["column2"];
> 	}
> To access a single item (for a unique $id) use $results[$id]["column1"].
> Because this method is foreach friendly you can save yourself a lot of
> time dealing with the results. If you array_push the rows into an array of
> results you end up with both [0] and ["named"] keys in your array, which
> makes life infinitely more complicated.
> </tip>
> PS If anyone knows a more effecient way of doing the above, I'd love to
> know. Right now I have to set each column individually (i.e. repeat the
> $results["values"] = $rows["values] line). At least what I'm doing now is
> about 100 times more useful than having array_pushed rows.

If you are going to have a lot of results, you could eat up a lot of memory 
with this technique Doing what you need to do with the resultset inside the 
while() loop is generally the best practice.

that said, you could do:
	while ($rows = mysql_fetch_array($mysql_query)) {
 		foreach ($rows as $k=>$v) {
			if ($k == 'id') continue;
			$results[$rows["id"]][$k] = $v;

More information about the thelist mailing list