Defining Variables within Functions and then Retrieving them

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
JCoster
Forum Newbie
Posts: 2
Joined: Tue May 20, 2008 8:51 am

Defining Variables within Functions and then Retrieving them

Post by JCoster »

I've done a lot of PHP before but never really properly got into using tailormade functions to tidy up the code and reduce file sizes (normally just copy and apste the same algorithms and MySQL queries) which I know is bad practise.

Yet now I'm trying to sort this out and I've started a project which I'm intent on using functions for most of it.

Anyway, I'm basically having problems getting variables defined in functions out of them (I'm not even sure if you can?).

So say for example I have a MySQL query in a function such as this:

Code: Select all

    
function list_shows($showid) {
$showquery = mysql_query("SELECT * FROM shows WHERE showid = '$showid'") or die(mysql_error());
$showresult = mysql_fetch_array($showquery);
}
And then when I call this function from a different page, I want to call variables such as:

Code: Select all

$showresult[showid]
$showresult[name]
$showresult[status]
So because these variables have been defined in the result from the query in the function, why can I not call them on the other page after calling the function?

Thanks for your help.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Defining Variables within Functions and then Retrieving them

Post by onion2k »

Have you read the PHP manual page about functions? http://uk3.php.net/manual/en/language.functions.php ... you want the section about returning things.
JCoster
Forum Newbie
Posts: 2
Joined: Tue May 20, 2008 8:51 am

Re: Defining Variables within Functions and then Retrieving them

Post by JCoster »

Ok, brilliant thanks for your help I have it sorted.

With this as my function:

Code: Select all

function query_show($showid) {
    $showquery = mysql_query("SELECT * FROM shows WHERE showid = '$showid'") or die(mysql_error());
    $showresult = mysql_fetch_array($showquery);
    return $showresult;
}
I can call the values from the array if I call the function with the following:

Code: Select all

$showresult = query_show($_GET['sid']);
With this I can now display the contents of the array as before with, for example:

Code: Select all

$showresult[showid]
$showresult[name]
$showresult[status]
Thank you once again.
Post Reply