Re: smarter code (mySQL arrays)
| From: | Michael Sims | Date: | Tue, 22 Jan 2002 01:11:19 +0000 |
| Subject: | Re: smarter code (mySQL arrays) | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-81463@lists.php.net to get a copy of this message | ||
At 11:12 AM 1/22/2002 +1100, Justin French wrote:
Hi all, I've got into the habbit of pulling data out of a table something like this: [...]
$id = $sql_myrow["id"]; $date = $sql_myrow["date"]; [...]
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.Personally I find it much easier to work with mysql_fetch_object(). In your scenario you are most likely setting $id = $sql_myrow["id"] because the former is easier to type and you're probably going to be referencing it more than once. But if you use mysql_fetch_object() you may decide that you don't need to do that anymore. For example: while ($row = mysql_fetch_object($result)) { echo "$row->artist - $row->title<br>"; } Much easier than echo $row["artist"]." - ".$row["title"]."<br>";
Then, it'd be great if I could automate this further to automaticaly to a stripslashes() on each var, then possibly nl2br() etc.Just curious, but why are you having to stripslashes() on the data coming out of the database? Do you have magic_quotes_runtime enabled on your server?
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)> }This is untested, but should work: while($sql_myrow = mysql_fetch_array($sql_result)) { foreach($sql_myrow as $key => $value) {
$$key=nl2br(stripslashes($value));} } Basically the foreach loop goes through each index of $sql_myrow and creates a variable by that name, setting it equal to the value of the index after it's had it's slashes stripped and it's br's newlined. :-)
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 :)The function Mr. Stancescu posted looks like it'll do the trick, with some modifications to perform the nl2br() and the stripslashes()...