Hello I am new to codeigniter framework, and I need help do get some data from array that is forwarded to my view.
In my controller's method I was load model who returns me data array from db, and than I pass that data to my view, and that looks like this:
function deleteAccount($data){
$this->load->model('model_admin');
$dataFromModel = array();
if($query = $this->model_admin->retrieveAccount ($data)){
$dataFromModel['records'] = $query;
$this->load->view('admin/test',$dataFromModel);
} else {
echo "No data was returned";
}
}
and in my view i manage to retrieve that data and to echo it like this:
<?php
echo "TEST page<br/>";
if(isset($records)) {
foreach ($records as $row) {
echo $row->username;
}
} else {
echo "No data";
}
?>
But I am certain that if I retrieve data from db it is either one line or no lines at all, so in my view page i would like to echo that data without foreach loop on some way, for example like this:
echo $records->username;
or:
echo $records[0]; //because it is the first argument in line
but in both ways it throws an error :
1 - first case: Trying to get property of non-object
2 - second case: Object of class stdClass could not be converted to string
This is my model:
function retrieveAccount($data){
$query = $this->db->get_where('table_users', array('username' => $data[2]));
return $query->result(); }
Can someone help me, and show me how to retrieve that data.
If you want to use $records->username this means $records must contain only one value. In this case instead of using $query->result(), use $query->row() in your model code.
You cannot echo stdClass object. $records[0] is stdClass object thus Php is giving this error. Instead this would work
echo $records[0]->username
Related
I have a 2d array $locations that is the result of a sql query. I can use the foreach function to get all of the rows, like this, and it works perfectly:
foreach($locations as $row) {
echo $row->NICKNAME;
echo $row->POC;
}
I just want to grab the first row of the index NICKNAME in the array. I try
echo $locations["NICKNAME"][0];
and it says "Undefined index: NICKNAME"
I try:
echo $locations[0][0];
and it says "Cannot use object of type stdClass as array"
When I echo gettype($locations) it prints the word array, and the foreach function (which is only for arrays right?) works, so I really don't understand that error.
I know this is simple but I don't know what else to try and Googling hasn't helped.
Try using this as $location is an array of objects and to reference each object, you have to use $location along with the key of the object you want to select. Once selected, use the the Nickname from it as a regular object property.
echo $locations[0]->NICKNAME;
i'm a newbie in codeigniter , just i got this error:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: views/coba.php
Line Number: 52
and still i can't solve it. this my code on controller:
public function getvalue()
{
$result = $this->admin_model->harga();
$data = array(
'harga' => $result,
);
if ($this->input->post('btnKirim')==true) {
$data['nama']=$this->input->post('nama');
$data['tgl_masuk']=$this->input->post('tgl_masuk');
$data['tgl_ambil']=$this->input->post('tgl_ambil');
$data['berat']=$this->input->post('berat');
$data['status']=$this->input->post('status');
}
$data['judul'] = 'Halaman Pegawai';
$data['content'] = 'coba';
$this->load->view('template/index',$data);
}
and this code for my model :
public function harga(){
$query= $this->db->query('SELECT harga from satuan');
return $query->result();
}
it's my view.php on where i got this error message:
<div class="form-group">
<label for="total" class="control-label">Total Harga</label>
<div>
<input name="total" id="total" type="numeric" class="form-control" value="<?php echo $harga; ?>" readonly='total'>
</div>
</div>
Why am I getting this message, what can I do to solve it?
Method result either returns an array of objects or an empty array. Either way, method harga returns an array.
Since you're using that result to populate value of a field, it's not clear if you really want all results from a table or just some specific, maybe even just one result. Whatever you want, you need to convert that to a scalar value to be able to use echo without warnings.
It's possible to iterate over returned results, so you could do something like this:
public function harga() {
// Since your HTML containts 'Total harga', I'm assuming you
// have multiple results and you need to add them all up
$result = 0
foreach($query->result() as $row) {
$output += $row->harga;
}
return $result;
}
If you need only one result, consider using $query->row() to get a single row from the table (and even better, use limit or where in your sql query).
To fully understand what your problem is, check the documentation.
you can try code :
$result = $this->admin_model->harga();
foreach($query->result() as $row) {
$data['harga']= $row->harga;
}
I have a query in my model using joins and returned the query results as array
result_array();
I then returned that result to my controller where i called the model.
$data = $this->Model->show();
foreach($data as $val)
{
$arr[$val['recipename']] = $val['componentname'];
}
if($data != null)
{
$this->load->view('Admin\success',$arr);
}
I didnt originally had $arr value. I just added it up there to make the array clearer. Anyhow, with or without.
var_dump($data) and var_dump($arr) or even if i $recipename or $componentname stll null.
returns null. says they are undefined.
I don't know what went wrong.
I read this other question. that is why i made the $arr so i could make it a single array and so when it transfers it will be extracted and tried to echo them but to no avail.
Codeigniter passing data from controller to view
EDIT:
query works fine, it returns values.
$sample = $this->db->select('recipe.recipename,component.componentname')->from('recipe')
->join('recipecomponent','recipe.recipeid = recipecomponent.recipeid')
->join('component','component.componentid = recipecomponent.componentid')
->group_by('recipe.recipeid')
->get()
->result_array();
return $sample;
Once you pass an array of data to your view the array keys are turned into variables. Say for example after your foreach loop your $arr variable is an array like this
array [
'cheese' => 'brie'
'cookie' => 'chocolate chips'
]
You would then access $arr['cheese'] by doing the following in the view
echo $cheese;
Trying to access $data or $arr in the view won't work because they are not in scope
$data is most likely empty and you are iterating an empty array.
A simple way to debug is found below:
Debugging an array or object:
echo '<div style="padding:15px; background-color:white;"><pre>'.print_r($data, true).'</pre></div>';
or
echo '<div style="padding:15px; background-color:white;"><pre>'.print_r($this->Model->show(), true).'</pre></div>';
You should also turn on error reporting in your __construct like so:
error_reporting(E_ALL);
If the print_r() shows you an empty array then your model is returning no data and the answer to your question is probably that you need to fix your query.
So I have this line of code in my controller:
$this->load->view('sampleview',$result);
So when I go into my view and try to echo result, either by foreach or directly writing
print_r($result);
it shows an error that it is an undefined variable.
But when I put the print_r($result); on my controller like this below:
function show()
{
$this->load->view('sampleview',$result);
print_r($result);
}
It would print on my sampleview page where I was redirected. I’m confused why this is happening.
EDIT
The whole controller would be: I have another view which I click an anchor tag with segment(3) as an id. Then I query that id to my model then pass it to another view for display.
$id = $this->uri->segment(3);
$result = $this->model->show($recipe_id);
if($result!=null)
{
$this->load->view('Admin_recipe_edit',$result);
}
You $result array will be extracted in your view. if you want as an array, then do it as
$data["result"] = $result;
$this->load->view('sampleview',$data);
Then do print_r($result); in view.
This is how you should have to make a array of data that you want to access on your view
// Your array
$result['Data_Array'] = array(....);
$this->load->view('sampleview',$result);
print_r($result);
Now Access like this in your View Section:
View
print_r($Data_Array);
Dude try to put $result in an array example$view_data['$result']=$result; then load the view exmaple $this->load->view(your_view,$view_data);. and in the view page try to print $result.exmaple print_r($result); .It will work I think so.
In CodeIgniter
$Data['result'] = $ArrayData;
$this->load->view('viewfile',$Data);
In View
print_r($result);
I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/