Re: smarter code (mySQL arrays)
| From: | David Robley | Date: | Tue, 22 Jan 2002 08:39:03 +0000 |
| Subject: | Re: smarter code (mySQL arrays) | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-81496@lists.php.net to get a copy of this message | ||
justin@indent.com.au (Justin French) wrote in
news:3C4CAE8A.208AB692@indent.com.au:
> Hi all,
>
> I've got into the habbit of pulling data out of a table something like
> this:
>
>
> $sql = "SELECT * FROM cd_review WHERE publish='yes' ORDER BY id DESC
> LIMIT 3";
> $sql_result = mysql_query($sql);
> print mysql_error();
> while ($sql_myrow = mysql_fetch_array($sql_result))
> {
> // pull out the data
> $id = $sql_myrow["id"];
> $date = $sql_myrow["date"];
> $user_id = $sql_myrow["user_id"];
> $artist = $sql_myrow["artist"];
> $title = $sql_myrow["title"];
> // edited out about 10 colums for clarity
> }
>
> Now, I reckon there must be a way of automating the task of making the
> $title var out of $sql_myrow["title"] etc etc for starters, which would
> really help on tables with lots of columns.
>
> Then, it'd be great if I could automate this further to automaticaly to
> a stripslashes() on each var, then possibly nl2br() etc.
>
>
> In psuedo-code I guess it looks something like:
>
> while($sql_myrow = mysql_fetch_array($sql_result))
> {
>
> // we have an array of one row
>
> <use a foreach loop to stripslashes() on each element of the array>
>
> <use a foreach loop to nl2br() on each element of the array>
>
> <use a foreach loop to take each element (eg $sql_myrow["id"]) and
> create a var ($id)>
>
> }
>
>
> Of course I'm a way newbie on arrays, and I've read the manual, but am
> unclear on the syntax for the above.
>
>
> Ultimately, I'd like to put this all into a function which I call that
> does it all in one hit, but I'll take that in a smaller step :)
>
>
> Justin French
Justin
There is a function extract() which will take an array and return the
key/value pairs as $key = value
So if you do
while($sql_myrow = mysql_fetch_array($sql_result))
extract($sql_myrow);
you can then refer to the field names as the same variable.
I have a vague recollection (its a couple of months since I retired!) that
you can apply functions like nl2br() to an array and they work on each
element of the array? Worth a try; it shouldn't take too long to test and
see if it works.
Cheers
--
David Robley
Temporary Kiwi!