0

I am not sure how to write the following code.

    $rowID = $_POST['rowID'];
    if ($listing = $Listings->getData($rowID)) {
        $jsonArray = array(

            'listing_number' => $listing['listing_number'],


        );
        exit(json_encode($jsonArray));
    }

When I do it like that, the response is Undefined Index: listing_number.

However, If I write it like this,

$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
    $jsonArray = array(

        'listing_number' => $listing[0],


    );
    exit(json_encode($jsonArray));
}

The response is

{"listing_number":{"id":"24","client_id":"1","address":"","address_2":"","city":"","state":"","zip":"","price":"","listing_number":"asdasdasdasd","remarks":"","link":"","status":"","bd":"","ba":"","lot_sz":"","sq_ft":"","yr":"","type":"","thumb":""}}

Which lets me know my SQL is and PHP is correct, I just don't know how to access $listing['listing_number] correctly.

Any help would be appreciated.

7
  • Where do you intend to access it from? PHP? JS? Commented May 10, 2019 at 12:45
  • 3
    You need to use $listing[0]['listing_number'] edit: You said it's an stdClass, so you need to use $listing[0]->listing_number Commented May 10, 2019 at 12:46
  • $listing = $Listings->getData($rowID) this data may be array and therefore getting index 0 will give you 1 record. Then you can get "listing_number" of that data. Commented May 10, 2019 at 12:46
  • @GrumpyCrouton When I do $listing[0]["listing_number"]. I get this error, "Fatal error: Uncaught Error: Cannot use object of type stdClass as array" Commented May 10, 2019 at 12:47
  • 1
    @KevinM1990112qwq it is because of that data in index 0 may be object. therefore you must get it like $listing[0]->listing_number Commented May 10, 2019 at 12:47

1 Answer 1

1

as GrumpCrouton said in the comment, your query is returning an array of results. So if you want to access a value in the first result, you first need to access this result using it's index :
$listing[0]->listing_number.

$rowID = $_POST['rowID'];
if ($listing = $Listings->getData($rowID)) {
    $jsonArray = array(
        'listing_number' => $listing[0]->listing_number,
    );
    exit(json_encode($jsonArray));
}

P.S. You can convert object to array using a simple cast ( $result = (array) $result ), but it is not a must in your case. Casting your object to array will allow you to acces it's data using result['key'] rather than result->key.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.