0

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

6
  • print_r($product). And this $result[] = array(); is useless. So your first array element is empty array, which is not object. Commented Dec 5, 2016 at 8:12
  • so how should i do that yes first element is emppty Commented Dec 5, 2016 at 8:14
  • $result = array(); Commented Dec 5, 2016 at 8:14
  • Did you declare a class in that other file codec/functions.php? If the contents of that file is just a bunch of normal Custom Functions, you need not add Access Modifiers (like Public) to the Functions and you also don't need to call it on any object: that is — You'd call it directly... $products = products(); instead of $products = $object -> products();.... without $object-> Commented Dec 5, 2016 at 8:15
  • thanks solved proble Commented Dec 5, 2016 at 8:16

1 Answer 1

1

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.

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.