(há uma versão portuguesa desta entrada)
Last night I was writing some PHP code – a simple upcoming feature for the blog – when i had to once again query the MySQL server, and use mysql_fetch_array()
to grab the returning data. Some of you probably use some fancy PHP Class to interface with the server, and you should. But for some odd reason i prefer to do this way.
So, i end up having an array – which i usually call $raw
– with a couple keys and values:
Array
(
[id] => 1
[field1] => test
[field2] => another test
)
Now, if you want to use this in a string, you either echo it like:
echo "this is the value of field1: " . $raw["field1"];
Or you stick it in a var and use it directly:
$field1 = $raw["field1"];
echo "this is the value of field1: $field1";
Ok, but most of the times you're simply creating a local variable with the same name as the key. So I came up with a very short function to pull out the variables from the array. It can also be useful to extract session variables, but it can be used pretty much in every similar situation.
function pull_vars( $target ) {
foreach( $target as $key => $val ) {
global $$key;
$$key = $val;
}
}
Attention This can cause some clash between these and other variables. Be careful with the names of the variables used. If this happens, you can solve it by giving an alias to the fields in the MySQL query: $sql = "select title as ptitle, datetime as dt, (...)
.
Stick this in a file called pull_vars.php
. Now include it on top of every page and call it every time you need to unpack the variables in the array returned by the MySQL server. Just for the sake of completeness, here's how you call the function:
pull_vars( $raw );
Thought i'd share this little tip, might be helpful to some of you. ;)