Re: Array?

From: Date: Fri, 06 Oct 2000 20:00:23 +0000
Subject: Re: Array?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-18966@lists.php.net to get a copy of this message
On Fri, 6 Oct 2000, Joao Prado Maia wrote: > On Fri, 6 Oct 2000, Wee Chua wrote: > > > Hi all, > > I am newbie to PHP. How could call each field out manully from this array? > > Thanks in advance for any helps! > > > > $result = @mysql_query("Select * from > > Project,ProjType,Company,Event,EventType",$db); > > for ($i=0;$i<mysql_num_fields($result);$i++) { > > > > $field = mysql_field_name($result,$i); > > > > <?php > // sweet code to dynamically get all values from all fields > // and create dynamic variables with their names > $sql = "SELECT * FROM Project"; > $result = @mysql_query($sql, $db); > $rows = @mysql_num_rows($result); > for ($i = 0; $i < $rows; $i++) { > $fields = mysql_num_fields($result); > for ($y = 0; $y < $fields; $y++) { > $field_name = mysql_field_name($result, $y); > $$field_name = mysql_result($result, $i, $y); > } > } > ?> > > Thats sweet ;) Perhaps, but it's also extremely inefficient. mysql_result isn't intended to be used in that manner. Besides, the end result will be only 5 variables, $Project, $ProjType, $Company, $Event, and $EventType, set to the last values that they had in the SQL result. In the above code, you're grabbing a single cell from the result set multiple times ($rows * $fields times, actually). A much faster alternative would be to use mysql_fetch_row() or mysql_fetch_array(), which grabs data one row at a time. Also, if you want to pull out a variable per field for a row set, you could simply do while ($row = mysql_fetch_array($result)) { extract($row); // Now you have $Project, $ProjType, $Company, $Event, and $EventType // But they will all be reassigned in the next iteration of the loop. } Matt

« previous php.general (#18966) next »