Waleed Ikhlaq
Waleed Ikhlaq

Reputation: 39

Trying to get non-object Using OOP method

Hi i have made a function in which i am getting results from db and storing it to an array and returned an array to the function. Below is the function:

public function products() {

        shopping::connection();
        $get = mysqli_query($this -> connection, 'Select * from products limit 5');
        $result[] = array();
        while($results = mysqli_fetch_object($get)) {
            $result[] = $results;
        }
        return $result;

    }

so now this function is another file called functions.php i called this file into another file where i want to pull all the data and display on that page so i included the file and stored the function in variable. Below how i did

<?php require_once('codec/functions.php'); ?>
<?php $products = $object -> products(); ?>

Now if i do print_r($products) gives me an array of data, but when i try to retrieve the data using this function

<?php echo $product -> price; ?>

It gives me an error of

Notice: Trying to get property of non-object in C:\xampp\htdocs\Shopping\index.php on line 15

I did search on google but didn't found result that i want. Please tell me what i am doing wrong. Thanks

Upvotes: 0

Views: 32

Answers (1)

Vasil Rashkov
Vasil Rashkov

Reputation: 1830

You are trying to access a property of a non-object. As the error tells you.

There is a huge difference between objects and arrays.

You have an array of products, which is also an object.

If you want to access the data from the db, you need to loop the results.

foreach ($products as $product) { // where $product is a single row from your query
    echo $product->price; // here you take the price of a single product.
}

You also have a problem with initializing your $result variable in the function products. It will always have an empty array on the first index. Try $result = array(); so that you wont have any problems.

Upvotes: 1

Related Questions