Beginner PHP Question - Access Data from Function
I have this function:
function selectValue($test) {
$connection = dbConnect(HOST, USERNAME, PASSWORD, DATABASE);
$query = "SELECT * FROM table where value = '$test'";
$results = @mysql_query($query, $connection);
$value = mysql_fe开发者_Go百科tch_assoc($results);
}
selectValue('abcde');
echo $value['something'];
This results in $value becoming an array. I would like to access this array from outside of the function. I tried to do this using the last line of code above (ie. echo...) but this doesn't work. How should I do this?
You need to return a value from your function:
function selectValue($test) {
$connection = dbConnect(HOST, USERNAME, PASSWORD, DATABASE);
$query = "SELECT * FROM pans where value = '$test'";
$results = @mysql_query($query, $connection);
$value = mysql_fetch_assoc($results);
return $value;
}
$value = selectValue('abcde');
echo $value['something'];
Be aware that the function could fail at various places, so you should not always assume that the return value will contain the result from mysql_fetch_assoc
.
One way to do that (one way of many) is to test the return value before using it:
function selectValue($test) {
$value = false;
$connection = dbConnect(HOST, USERNAME, PASSWORD, DATABASE);
$query = "SELECT * FROM pans where value = '$test'";
$results = @mysql_query($query, $connection);
$value = mysql_fetch_assoc($results);
return $value;
}
if($value = selectValue('abcde')) {
echo $value['something'];
} else {
echo "Something went wrong.\n";
}
Exception handling is another way to handle errors.
function selectValue($test) {
$connection = dbConnect(HOST, USERNAME, PASSWORD, DATABASE);
$query = "SELECT * FROM table where value = '$test'";
$results = @mysql_query($query, $connection);
$value = mysql_fetch_assoc($results);
return $value;
}
$value = selectValue('abcde');
echo $value['something'];
Put the return
keyword in your function:
function selectValue($test) {
$connection = dbConnect(HOST, USERNAME, PASSWORD, DATABASE);
$query = "SELECT * FROM pans where value = '$test'";
$results = @mysql_query($query, $connection);
$value = mysql_fetch_assoc($results);
return $value; // return the value
}
You can return value from the function - here I rewrote it for you:
function selectValue($test) {
$connection = dbConnect(HOST, USERNAME, PASSWORD, DATABASE);
$query = "SELECT * FROM pans where value = '$test'";
$results = @mysql_query($query, $connection);
$value = mysql_fetch_assoc($results);
return $value;
}
$val = selectValue('abcde');
echo $val['something'];
I assume you have already defined $value outside that function? Otherwise you need to return it so you can access it outside the function.
return the value
return $value
or use globals
. but globals are not state of the art anymore and shouldn't be used.
This may help
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
精彩评论