Trying to teach myself php and I am struggling with what I think is a scoping issue?
I have a query, while loop, if/else and a function.
I would like to echo the results of the function get_patronapi_data($id) within my while loop.
My code so far is as follows (stripped for legibility);
$stmt = $conn->prepare("SELECT... ..."); //QUERY here ...
if( $stmt->num_rows > 0 )
{
while ($stmt->fetch()) {
if (SomethingIsTrue){
echo get_patronapi_data($id);
}
else {
echo $somethingElse;
}
}//end while
}//end if
define("APISERVER", "http://mydomain:4500");
function get_patronapi_data($id) {
$apiurl = "APISERVER" . "/PATRONAPI/$id/dump";//line 135
$api_contents = get_api_contents($apiurl);
$api_array_lines = explode("\n", $api_contents);
foreach($api_array_lines as $line){
if(strpos($line, "EXP DATE") !== false){
$data = explode("=", $line);
return $data[1];
}//end if
}//end foreach
}//end function
function get_api_contents($apiurl) {
$api_contents = file_get_contents($apiurl);//line 154
$api_contents = trim(strip_tags($api_contents));
return $api_contents;
}//end function
echo get_patronapi_data($id); // this works and echoes $data on screen
Whenever I echo get_patronapi_data($id); outside of the functions I successfully see the data on screen. However when I echo get_patronapi_data($id); within the loop I receive the following errors;
Notice: Use of undefined constant APISERVER - assumed 'APISERVER' in C:\xampp...search_1.php on line 135
Warning: file_get_contents(APISERVER/PATRONAPI/3047468/dump): failed to open stream: No such file or directory in C:\xampp...search_1.php on line 154
I'm sure I am doing something very silly however any help is appreciated.
$dataanywhere in thewhileloop. (maybe you meantwhile ($data = $stmt->fetch())?)APISERVER. It's treated as a constant php.net/manual/en/function.constant.php. Either you define it as a constant, or wrap it in quotes.define("APISERVER", "http://xxxxxxxxxxxx");as your very first line.function get_patronapi_data($conn, $id) {and apply the same when calling the function. and possibly forfunction get_api_contents($apiurl) {also. or make it available within the global scope.