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
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.
Related
In my Symfony project I am returning all objects with Doctrine query builder defined with Paginator.
When dumping $posts['data'], response is on the image: IMAGE
When entering the loop and dumping first result, this is what I get: IMAGE
I want on each array object to assign new key-value pair. Every array object has destinationId (you can see on the image), and I have a method that searches for the name by that param.
I want to assign that new value to every object in foreach.
Code:
$posts = $this->entityManager->getRepository(Post::class)->getPage();
foreach ($posts['data'] as $postsData) {
foreach ($postsData as $post) {
$destinationName = $this->destinationService->getDestinationNameById(
$post->getDestinationId()
);
$postsData['destinationName'] = $destinationName;
}
}
Error is:
Call to a member function getDestinationId() on string
This is very odd as this field has entity type defined as string and also when dumping
dump($post->getDestinationId());
I get: "107869901061558" which is string.
It's because you override you $postsData variable.
You need to use a different variable to store your $destinationName like this :
$posts = $this->entityManager->getRepository(Post::class)->getPage();
$destinationNames = [];
foreach ($posts['data'] as $postsData) {
foreach ($postsData as $post) {
$destinationName = $this->destinationService->getDestinationNameById(
$post->getDestinationId()
);
$destinationNames[$post->getId()] = $destinationName;
}
}
Like this, you could send $destinationNames to your template and find the right $destinationName thanks to the index.
This will probably be tagged as duplicate but might as well try since I can't get a specific solution.
my controller function seems to result to "Trying to get property of non-object" error. I want to get a specific data from an index of an array. the array is from a Session data that I used in another page.
function within my controller
public function checkPwd()
{
$oldPwd = $this->input->post('oldPass');//getting POST data from ajax
$newPwd = $this->input->post('newPass');//getting POST data from ajax
$currLogged = $this->session->all_userdata();
foreach ($currLogged as $log)
{
echo $log->pwd; //this results to Trying to get property of non-object
}
}
You can access it as
echo $currLogged['logged'][0]->pwd
In foreach you can access it as
foreach($currLogged as $log){
echo $log[0]->pwd;
}
I consider myself as a php beginner, so it may be possible that this question is too easy for someone, but I got really confused on how to solve it. I am trying to loop something from the database in my views. So, in a quick way I solved it like this:
I've created a function in my model that does the loop and in the same time is creating the html and saves it in a variable. Then, I get that variable from my controller and I pass it in my view. But, it seems that this is not a good way to solve it, since if I want to change my html I need to enter my model function instead some of the view files.
Then, I've created another function in my model that looks like this:
function displayUsers() {
$sql = $this->pdo->prepare('select * from user');
$sql->execute();
while($row = $sql->fetch())
$results[] = $row;
return $results;
}
Now... I take the result in my controller, and send it in the view, but then... I don't know how to extract the results from my variable. I have done something like this:
while($output) {
foreach($output[$i] as $key => $value)
$data[$key] = $value;
echo $data['email'];
$i++;
}
But then, in the end it says to me undefined offset, which means I am referring to an array key that doesn't exist. Can anyone help me on how to solve this issue?
Proper MVC shouldn't have any output in the model or the controller.
Ideally you would have a model that just gets the raw data and returns it in the controller. The controller can then build up an array of values that we'll call data. For example:
Controller
$data['users'] = $this->MyModel->getusers(); // Getting the users from your model
$data['posts'] = $this->MyModel->getposts(); // Getting the posts from your model
$this->getTemplate('userdisplay', $data); // Get the template userdisplay and pass data
This gets the data from the model, and then assigns it to a key within the "data" variable. You can then pass the data variable into the template. You'll then have two variables to work with in the template, $users and $posts.
You'll need a "getTemplate" function that properly maps the data array to individual variables for use in the template, but all of the display should be located in the template.
To answer your specific question at the end, something like this should work in the template:
if (count($users) > 0) {
foreach ($users as $person) {
echo $person['email'];
}
}
You should be able to do this:
foreach($output as $row) {
echo $row['email'];
}
I'm having trouble getting the results of a has_many query using php idiorm/paris. Following the example from the paris site the has_many result for posts returns as an object.
That's great, and I can run through the object and access individual methods, but what I want to be able to do is pass the result set as an associative array off to my template engine for display.
Example:
class Post extends Model {
}
class User extends Model {
public function posts() {
return $this->has_many('Post'); // Note we use the model name literally - not a pluralised version
}
}
The api works this way:
// Select a particular user from the database
$user = Model::factory('User')->find_one($user_id);
// Find the posts associated with the user
$posts = $user->posts()->find_many();
I am able to access the posts object and print the result set like this:
// echo each post id
foreach ($posts as $post) {
echo $post->id;
}
What I'd really like to be to do though, is use as_array() to get the entire resultset as an associative array, limited by certain fields in the way as_array works for an individual row, e.g.
$post_list = $posts()->as_array(id,title,post,date);
This, or a call on something like $user->posts()->find_many()->as_array() don't work.
What is the correct way to access this type of result set using paris?
Adding this method to idiorm.php gives me the desired functionality.
public function find_array() {
if (func_num_args() === 0) {
return $this->_run();
}
$args = func_get_args();
$array = array();
foreach ($this->_run() as $r) {
$array[] = array_intersect_key($r, array_flip($args));
}
return $array;
}
Now I can call $post_list = $posts()->find_array(); or $posts()->find_array('id','title'); etc.
find_one returns a Model object, find_many returns an array of Models.
If you want to get the entire result set as an array of associative array, one solution should be to use array_map
function model_as_array($model) {
return $model->as_array();
}
$posts = $user->posts()->find_many();
$my_view->posts = array_map(model_as_array, $posts);
var_dump($my_view->posts);
or in php 5.3+ (not tested)
$aa_posts = array_map(function($model) {return $model->as_array();} , $posts);
So I'm having this problem, it should be pretty simple, but I don't know why I can't figure it out. I"m new to the whole idea of MVC, and I'm trying to pass a database query from my controller into a view and display the results in the view. The way I'm doing it now says "undefined variable, sql" when I load the view. This is what I have:
CONTROLLER
function make_login()
{
//Select list of departments for dropdown
$this->load->database();
$sql = $this->db->query('SELECT departmentName FROM department ORDER BY departmentName ASC');
$this->load->view('siteheader.php');
$this->load->view('makelogin.php', $sql->result_array());
$this->load->view('sitefooter.php');
}
VIEW
<?php
foreach($sql->result_array() as $row)
{
echo $row['departmentName'];
}
?>
(If I just echo it out in the controller, it displays the results)
Any help would be awesome...
THANKS!
few tips ~
your make_login should be in a model. your controller will look something like this:
function make_login
{
$this->load->model('login_model'); // whatever you call it
$data['departments'] = $this->login_model->get_departments();
/* note - you don't need to have the extension when it's a php file */
$this->load->view('siteheader');
$this->load->view('makelogin', $data);
$this->load->view('sitefooter');
}
now in your model, have something like:
function get_departments()
{
$sql = $this->db->query('SELECT departmentName FROM department ORDER BY departmentName ASC');
return $sql->result();
/* you simply return the results as an object
* also note you can use the ActiveRecord class for this...might make it easier
*/
}
and finally, your view:
<?php
foreach($departments as $store)
{
echo $store->name . '<br />'; // your fields/whatever you want to output.
}
?>
The SQL query should be done in the model.
Cheap mnemonic device: the D in model = database.
In the Controller, you assign part of the $data array to the results of the query:
$this->load->model('blog_model');
$data['posts'] = $this->blog_model->getPosts();
// Load the view with the data
$this->load->view('blog', $data);
In the Model, you do the actual query:
public function getPosts()
{
// Method chaining supported in PHP 5
$this->db->select('*')->from('posts');
// Assign the query object to a variable
$query = $this->db->get();
// We don't want to return an empty result, so let's handle that error somehow
if (!$query->num_rows() > 0) {
die("There are no posts in the database.");
}
// Make a new array for the posts
$posts = array();
// For the purposes of this example, we'll only return the title
foreach ($query->result() as $row) {
$posts[$row->id] = $row->title;
}
// Pass the result back to the controller
return $posts;
}
Now, in the view, each element of $data will be its own variable:
<div class="post">
<?php foreach ($posts as $id => $title) : ?>
<h1 class="post-title"><?php echo $title; ?> (ID: <?php echo $id; ?>)</h1>
<p class="post-content">
.......
</p>
<?php endforeach; ?>
</div>
That's it!
It seems that either CI is confusing you or you are also new to PHP. They are just functions so you can't pass variables like that.
When passing an associative array it will take the key and make that into a variable with the value in the array, using native PHP functions. What Ross said is exactly what you are supposed to do.
Model: all database stuff
Controller: uses models to pass variables to views
View: outputs the variables (a view should never have any sql in it)
Also note that result and result_array have the same data but result returns objects and result_array returns associative arrays.
foreach($array as $row)
{
echo $row['departmentName'];
}
?>
You need to pass the $array in.
I am not sure what ->load->view() does and how it treats the incoming parameters.