开发者

Re-use variable outside of function?

How can I use return the $row array in the below example, so that I can re-use the variable outside of this function?

I manage to echo the information inside the function using $row['columnName'], but various combinations of global and $GLOBALS, return $xyz and getting variable scope to work for me has me a bit out of my depth. Any answers please?

<?php
function getInfo() {

    $query = /* Some SQL Query */;

    $result开发者_如何学编程 = mysql_query($query); 

    if($result == false) 
    { 
       user_error("Query failed: " . mysql_error() . "<br />\n$query"); 
    } 
    elseif(mysql_num_rows($result) == 0) 
    { 
       echo "<p>Sorry, no rows were returned by your query.</p>\n"; 
    } 
    else 
    { 
    while ($row = mysql_fetch_assoc($result)) {
        /* What goes here? */
        }
    } 

}
?>


Just return it from your function:

$results = array();
while ($row = mysql_fetch_assoc($result)) {
    $results[] = $row;    // or do something more with the row
}
return $results;

and call your function like:

$query_results = getInfo();


function getInfo() {

    $query = /* Some SQL Query */;

    $result = mysql_query($query); 

    if($result == false) 
    { 
       user_error("Query failed: " . mysql_error() . "<br />\n$query"); 
    } 
    elseif(mysql_num_rows($result) == 0) 
    { 
       echo "<p>Sorry, no rows were returned by your query.</p>\n"; 
    } 
    else 
    { 

    $data = array();

    while ($row = mysql_fetch_assoc($result)) {

           $data[] = $row;
        }

     return $data;
    } 

}

Then you just do: $mydata = getInfo();


You can either use $row directly inside the while block, or you can pass it as a parameter to another function that performs the row-level processing. First, define the function:

function processRow($r)
{
  echo $r['columnName'];
}

Then, inside your loop, call that function:

while ($row = mysql_fetch_assoc($result)) {
  processRow($row);
}

Within that function, the value known as $row in getInfo will be known as $r. (You can name the formal parameter $row if you want, but I've used a different name here just to illustrate that they don't need to have the same name. If you're not clear on variable scope, then giving lots of variables the same name may just serve to confuse yourself more.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜