[UPHPU] Mysql select to an array

Jacob Fugal jacob at fugal.net
Wed Aug 27 09:21:50 MDT 2003


On Wed, 2003-08-27 at 09:13, Mitch Anderson wrote:
> 	for($i=0; $i<$sched_num; $i++){
> 		$sched_array[$i] = mysql_fetch_row($sched_result);
> 	}
<snip>
> I want the function to return an array of the values (1,2,etc...) but
> with that for loop... it creates an array that contains two arrays, with
> those two values.  If that makes sense... If I drop the for loop... it
> replaces the value of the array with the new value (ie: $sched_array[0]
> = 2 at the end of the loop, but after the first time through
> $sched_array[0] = 1)

mysql_fetch_row returns an array, since the generic result of a query is
a set of tuples (easily represented by an array). In your case, the
results are one-tuples, but generically they are still tuples and
represented by an array. What you should try is something like this:

  for ($i = 0; $i < $sched_num; $i++)
  {
      $row = mysql_fetch_row($sched_result);
      $sched_array[$i] = $row[0];
  }

Alternately, and at this point I'm not entirely sure of syntax -- I'm
more experienced in Perl than PHP -- mysql_fetch_row should return null,
or an empty array or something else that tests false (I'm pretty sure
it's null) if there are no rows left to fetch. So you can do something
like:

  $i = 0;
  while ($row = mysql_fetch_row($sched_result))
  {
      $sched_array[$i++] = $row[0];
  }

And eliminate the need for $sched_num. One further step that I don't
even know if it's possible in PHP (I'll use perl as an example) is using
'push' to add elements to an array:

  while (@row = $sched_result->fetch_array)
  {
      push @sched_array, $row[0];
  }

Then you don't even need $i. Pretty nice, if PHP has an equivalent to
Perl's 'push'.

Jacob




More information about the UPHPU mailing list