[aklug] Re: Noob php question

From: Christopher Howard <choward@indicium.us>
Date: Wed Jun 03 2009 - 13:43:10 AKDT

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

John Martin wrote:
> Christopher,
>
> You need to iterate through the result set, like so:
>
> $query = sprintf("select username from robots.acct where type='teacher'");
> $result = mysql_query($query, $link);
>
> while ($row = mysql_fetch_array($result)) {
> echo "<option value='" . $row[0] . "'>" . $row[0] . "</option>";
> }
>
> HTH,
>
> -John
>
>
> -----Original Message-----
> From: aklug-bounce@aklug.org [mailto:aklug-bounce@aklug.org] On Behalf Of
> Christopher Howard
> Sent: Wednesday, June 03, 2009 1:17 PM
> To: Alaska Linux Users Group
> Subject: [aklug] Noob php question
>
> Hi. Trying to write some PHP/MySQL at work, without really knowing what
> I'm doing. :] Hoped somebody could answer a small question. Here's my code:
>
> ...
> $query = sprintf("select username from robots.acct where type='teacher'");
> $result = mysql_query($query, $link);
> $result = mysql_fetch_array($result);
> foreach($result as $t_username)
> {
> echo "<option value='" . $t_username . "'>" . $t_username . "</option>";
> }
> ...
>
> The output is inside a <select> tag in a form, so I want to create a
> selection box using values pulled from the MySQL database. When I run
> the same query in the MySQL client, I get this:
>
> mysql> select username from robots.acct where type='teacher';
> +----------+
> | username |
> +----------+
> | teacher1 |
> | teacher2 |
> +----------+
> 2 rows in set (0.00 sec)
>
> However, the output spit out by the php only provides me with two
> values: "teacher1" and "teacher1".
>
> I'm guessing this is either because I'm not supposed to be using
> mysql_fetch_array(), or because I am not properly handling what
> mysql_fetch_array() returns. Could someone point me in the right direction?
>

Thanks everyone - John's code worked for me. I didn't understand that
mysql_fetch_array was an iterator.

I wonder how it does that, i.e., does it modify $result some how each
time mysql_fetch_array is run on it? Well, I guess if we really cared
about that then we wouldn't be using PHP... :]

- --
Christopher Howard
http://indicium.us
http://theologia.indicium.us

I digitally sign /all/ of my e-mails via PGP. If you receive any e-mail
from me without my valid PGP signature, please take additional steps to
verify the authenticity of the message.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkom7m4ACgkQQ5FLNdi0BcXATACglF2/m2DvTxEuNgc3/sZcTDBK
TlsAn150q50Elwq3GPjKW8t/V+4NUjah
=jj/T
-----END PGP SIGNATURE-----
---------
To unsubscribe, send email to <aklug-request@aklug.org>
with 'unsubscribe' in the message body.
Received on Wed Jun 3 13:43:25 2009

This archive was generated by hypermail 2.1.8 : Wed Jun 03 2009 - 13:43:25 AKDT