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;
}
Related
I have a codeigniter problem. Im trying to send data from a controller , to a library , to a view.
i get this error in the view:
Message: Undefined variable: crimes
FileName: views/crime_view.php
Line: 45
while debugging , i dump the $data variable, and get:
that shows that my variables exist.
in the library , im getting the controller data by using:
$data[] = $componentData;
that would not work in this case. but if i in the library do:
$data['crimes'] = "test";
then it will work. for some reason it wont process the incomming arrays from the controller.
how can i get this to work?
full code:
function renderComponent($componentData = array())
{
$data[] = $componentData; // stores controller variables.
$data['rankDetails'] = $this->CI->user->rank_for_xp($userId);
var_dump($data);
$this->CI->load->view('components/crime/views/crime_view', $data);
}
example from the controller:
Q: How can i fix this to get it passing the variables needed? so i acually can get to use the $wait variable in the view?
You have a two dimensional array.
I think somewhere $data[] = ... must be $data = ...
to debug your arrays you could do like this:
echo '<pre>';
print_r($data);
echo '</pre>';
This shows clearly that your array is in another array...
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
I am following this documentation
to implement export to Excel in my laravel 4 project.
So am trying to generate excel file from array like this:
//$results is taken with db query
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = $result;
}
Excel::create('Filename', function($excel) use($data) {
$excel->sheet('Sheetname', function($sheet) use($data) {
$sheet->fromArray($data);
});
})->export('xls');
But this raises exception:
Object of class stdClass could not be converted to string
What am I doing wrong ?
UPDATE:
Tried this:
$data = get_object_vars($data);
which results in:
get_object_vars() expects parameter 1 to be object, array given
This:
$data = (array)$data;
Results in the initial error.
Try this simple in one line of code:-
$data= json_decode( json_encode($data), true);
Hope it helps :)
$data is indeed an array, but it's made up of objects.
Convert its content to array before creating it:
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = (array)$result;
#or first convert it and then change its properties using
#an array syntax, it's up to you
}
Excel::create(....
You might need to change your object to an array first. I dont know what export does, but I assume its expecting an array.
You can either use
get_object_vars()
Or if its a simple object, you can just typecast it.
$arr = (array) $Object;
If you have a Collection of stdClass objects, you could try with this:
$data = $data->map(function ($item){
return get_object_vars($item);
});
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country in another function as return value, (string), taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
This is easy all you need to do is something like this Grab your contents like this
$result->get(filed1) = 'some modification';
$result->get(filed2) = 'some modification2';
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.
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/