Page 1 of 1

Defining Variables within Functions and then Retrieving them

Posted: Tue May 20, 2008 8:56 am
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.

Re: Defining Variables within Functions and then Retrieving them

Posted: Tue May 20, 2008 9:06 am
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.

Re: Defining Variables within Functions and then Retrieving them

Posted: Tue May 20, 2008 9:42 am
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.