Question

So I have been working on a school project and have gotten this code for a website to work sometimes but other times it returns the error:

Notice: Trying to get property of non-object in C:\xampp\htdocs\schoolproj\getdata.php on line 27

Notice: Trying to get property of non-object in C:\xampp\htdocs\schoolproj\getdata.php on line 27
Ask 
Notice: Trying to get property of non-object in C:\xampp\htdocs\schoolproj\getdata.php on line 39

Notice: Trying to get property of non-object in C:\xampp\htdocs\schoolproj\getdata.php on line 39

for the php code:

<html>
 <body>

  <?php echo $_POST['name']; ?>!<br>


<?php  

$endpoint = "http://query.yahooapis.com/v1/public/yql";

$ticker = "'".$_POST["ticker"]."'";
$query = urlencode("env 'store://datatables.org/alltableswithkeys';select * from yahoo.finance.quotes where symbol in (".$ticker.")");
$ch = curl_init($endpoint.'?q='.$query. '&format=json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

if (curl_error($ch)){
    die(curl_error($ch));
}
curl_close($ch);

//echo'<pre>';

$result = json_decode($result);


$symbol =  $result->query->results->quote->symbol;
print_r($symbol);




?>

Ask

<?php

$Ask = $result->query->results->quote->Ask;
print_r($Ask);

?>

 </body>
 </html> 

I was wondering if anyone had some advice as to how I could permanently fix the problem or have some sort of error handling. I am new to this so any help would be great. Thanks!

Was it helpful?

Solution

The problematic lines if the code you gave is the whole getdata.php file are:

  • l.27: $symbol = $result->query->results->quote->symbol;
  • l.39: $Ask = $result->query->results->quote->Ask;

And the error is telling you that at one point in this your are accessing a property of something that is not an object.

Considering you are saying it sometimes work and sometimes doesn't, it's likely that there are occasional errors, either in your query (depending on your input) or with datatables.org (see this old question on developer.yahoo which indicates that queries would fail when datatables.org doesn't respond).

Then if there is an error, the json you receive will have a structure like below (this is an error I got initially when trying your code because I had forgottent to enclose the ticker in quotes).

{
    "error": {
        "lang":"en-US",
        "description":"Query syntax error(s) [line 1:95 mismatched input 'in' expecting ISNOTNULL]"
    }
}

In this result you don't have the query attribute and thus is fails when you try to access it. You should then first check if there is an error (looking for the error attribute), and only if there is none try and access the query results.

To check for the error, you could use something like

if (property_exists($result, "error")) {
    // your error handling
} else {
    // your current code accessing the results
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top