Codeigniter Extracting Information, Function Isn't Working - database

I'm attempting to extract information from my mysql database. I believe I'm properly joining tables (function syntax below) but when I try and display the extracted information inside of a view, nothing is showing up. I used var_dump and my array is saying
array (size=0) empty
I'm also getting these error messages as well.
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_show_all_averages.php
Line Number: 6
Severity: Notice
Message: Undefined offset: 0
Filename: views/view_show_all_averages.php
Line Number: 7
My question is, where do you think I'm going wrong. What are some steps I should take to go about fixing my issue? (syntax below) Thanks Everyone.
My Model_data function
function getJoinInformation($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$query = $this->db->get();
return $query->result();
}
My Site Controller
public function getAllInformation($year,$make,$model)
{
if(is_null($year)) return false;
if(is_null($make)) return false;
if(is_null($model)) return false;
$this->load->model('model_data');
$data['allvehicledata'] = $this->model_data->getJoinInformation($year,$make,$model);
$this->load->view('view_show_all_averages',$data);
}
My View
<?php
var_dump($allvehicledata);
if(isset($allvehicledata) && !is_null($allvehicledata))
{
echo $allvehicledata->make. ' ' .$allvehicledata->model . "<br />";
$make = $allvehicledata[0]->make;
echo "$make";
// $state = $cities[0]->state;
// echo '<hr>';
foreach ($allvehicledata as $car)
{
echo anchor('site/getAllInformation/'.$car->year.'/'.$car->make.'/'.$car->model, $car->year.' '.$car->make.' '.$car->model, array('title'=>$car->make.' '.$car->model)).'<br>';
}
}
?>

Your notice errors are happening because you are returning an array from your model function, yet are calling the data like it is an object. If you only want to retrieve one row of data from the DB, use row() instead of result(). Read Generating Query Results for more info.
The query you're running is not failing, but it is not returning any results. Chances are your WHERE conditions are not being given the values that you assume they are (that's my guess, anyway).
Use echo $this->db->last_query() after you perform the DB query to see exactly what SQL is being sent, and use that to figure out what may be wrong and why the result set is empty.

Related

INSERT INTO sqlsrv_query not working

I'm trying to add records to a table with no success :( and even if the record is not added to the DB, it returns no error... I get "Ok" returned...
I know my connection is working cause when I change my query to FETCH info from that same table, it works.
public static function Test($pConn,$pNumEmploye,$pPrenom)
{
$query = "INSERT INTO [Test] ([NumEmploye],[Prenom]) VALUES(?,?)";
$params = array('12','test');
if(!sqlsrv_query($pConn,$query,$params))
{die( print_r( sqlsrv_errors(), true));}
else {return "ok";}
}
Please help before I go insane :)
Your code check doesn't check to see if the record has actually be imported into the database, that will only check if there is any errors, in your case there isn't any errors, so it will return false, and hence ok.
if(!sqlsrv_query($pConn,$query,$params))
{die( print_r( sqlsrv_errors(), true));}
else {return "ok";}
Meaning you need to use something else, such as sqlsrv_fetch function, in your case sqlsrv_rows_affected will probably work.

How to report errors on non-column input fields

I have a form for creating a batch of events. It's got inputs for name, description, location, start and end time, all of which are columns in the events table. It's also got a number of inputs for dates, using field names like dates.0.date, dates.1.date, etc.
echo $this->Form->input('name');
echo $this->Form->input('description');
echo $this->Form->input('location');
echo $this->Form->input('start');
echo $this->Form->input('end');
for ($i = 0; $i < $this->request->data['repeat_count']; ++ $i) {
echo $this->Form->input("dates.$i.date", ['type' => 'date']);
}
The save process loops through the dates array in the submitted input, creating an entity with the rest of the data and the date for each one, and saving it. That is, the resulting entities will have fields called name, description, location, start, end and date. (Hope that's clear!) This part works great, and it's wrapped in a transactional function so that the events are only saved if all succeed.
$event = $this->Events->newEntity(array_merge(
$this->request->data, ['team_id' => $id, 'dates' => []]));
if (!$this->Events->connection()->transactional(function () use ($id, $event) {
for ($i = 0; $i < $this->request->data['repeat_count']; ++ $i) {
// Use $e for the entity that is actually saved, so the
// $event entity isn't mangled
$e = $this->Events->newEntity(array_merge(
$this->request->data,
[
'team_id' => $id,
'date' => $this->request->data['dates'][$i]['date']
]
));
$this->Events->save($e);
}
if ($event->errors()) {
$this->Flash->warning(__('The event could not be saved. Please correct the errors below and try again.'));
return false;
}
return false;
})) {
$this->set(compact('event'));
return;
}
The problem is when an invalid date is provided. The entity is not saved, and the error is correctly located in $e->errors('date'). But I can't figure out how to report that error back to the user on a date-by-date basis. Extrapolating from the entity documentation and using the dot notation that is standard elsewhere, I've tried $event->errors("dates.$i.date", $e->errors('date'));, and confirmed that any such errors are preserved in the list of errors in the entity when the view is rendered (i.e. if I use debug($event->errors());). But when I create the input fields, there are no error messages for the bad dates. They all have the submitted values in them, just no errors.
Tried using "date" instead of "dates" for the base of the field names (e.g. date.0.date instead of dates.0.date), to see if it was skipping the error check due to "dates" not being a column in the table, but this just caused a validation error at the point where I validate the rest of the data, so I didn't pursue that option any further.
I have some code elsewhere that sets the errors on associated entities which, if translated to this situation, would look like $event->dates[0]->errors($e->errors('date'));, but $event isn't associated with something called dates, so I don't see how to make this work here. I tried creating dates as an array in the $event entity, but assigning $event['dates'][$i] = $this->Events->newEntity(...); results in a PHP warning: "Indirect modification of overloaded element has no effect", and the entity is thrown away. Maybe manually create some ArrayContext object and assign the errors into that? Not immediately obvious to me how to do that.

Drupal 7 Unable to clear view cache in custom module

I have a view and it is responding fine for the filters I give. However when I run this multiple times in a for loop in my module, I get the same response for whichever filter I apply.
I searched the web and found code to turn off view caching. I have also disabled views data caching from structure->views->settings->advanced. But that is not working.
Below is the example code:
foreach ($term_ids as $term_id) {
$view2 = test_generate_view($view_name, $display_handler, $page, $count, $term_id);
echo "<pre>";
print_r($view2);
}
function test_generate_view($view_name, $display_handler, $page, $count, $term_id = null) {
$view = views_get_view($view_name, TRUE);
$view->set_display($display_handler);
if (!empty($term_id)) {
$term_item = $view->get_item($display_handler, 'filter', 'field_ref_issue_target_id');
$term_item['value']['value'] = $term_id;
$view->set_item($display_handler, 'filter', 'field_ref_issue_target_id', $term_item);
}
$view->init_pager();
$view->pager['items_per_page'] = $count;
$view->pager['use_pager'] = true;
$view->display_handler->options['use_pager'] = true;
$view->set_items_per_page($count);
$view->pager['current_page'] = $page;
$view->is_cacheable = FALSE;
$view->pre_execute();
$view->execute();
return $view;
}
If I don't run them in a loop and try separately for every term-id its working fine. But if I run them in a loop like above, the output is same for any term-id.
The code doesn't look so bad and because the filter changes, the caching should deliver a different result even if turned on. Because the code is working without the loop, maybe you should look into that. is $term_ids really an array of integer values or an array of term objects? If so, the function call would fall back to default which is null for term_ids and would not add a filter.
By the way: You should have a look at contextual filters which you can use really easily.

Difference in accessing variables in views

I've two controllers one is "Upload" which deals with images uploads and other is "Page" whid deals with the creation of pages of CMS now if in my "Upload" controller I load both the models i.e 'image_m' which deals with image upload and "page_m" which deals with the pages creation I've highlighted the relevant code my problem is if I access the variables in the view
$this->data['images'] = $this->image_m->get(); sent by this I can access in foreach loop as "$images->image_title, $images->image_path" etc
But the variable sent by this line ***$this->data['get_with_images'] = $this->page_m->get_no_parents();*** as $get_with_images->page_name, $get_with_images->page_id etc produces given error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: upload/index.php
Line Number: 20
what is the difference between these two access levels one for $image & other for $get_with_images because I can only access its values as $get_with_images
class Upload extends Admin_Controller {
public function __construct() {
parent::__construct();
***$this->load->model('image_m');
$this->load->model('page_m');***
}
public function index($id = NULL) {
//var_dump($this->data['images'] = $this->image_m->get_with_images());
//$this->data['images'] = $this->image_m->get_with_images();
***$this->data['images'] = $this->image_m->get();***
$this->data['subview'] = 'admin/upload/index';
if ($id) {
$this->data['image'] = $this->image_m->get($id);
count($this->data['image']) || $this->data['errors'][] = 'Page Could not be found';
}
$id == NULL || $this->data['image'] = $this->image_m->get($id);
/*this calls the page_m model function to load all the pages from pages table*/
***$this->data['get_with_images'] = $this->page_m->get_no_parents();***
You are not posting all your code so its hard to tell but is it because you used $this-> in the controller, but you haven't done the same thing in the view?
In this case i would recommend not using $this-> because its not necessary. Also its much better to check for errors etc when you call the model so do something like
if ( ! $data['images'] = $this->image_m->get($id) ) {
// Failure -- show an appropriate view for not getting any images
// am showing $data in case you have other values that are getting passed
$this->load->view( 'sadview', $data ); }
else {
// Success -- show a view to display images
$this->load->view( 'awesomeview', $data ); }
so we are saying if nothing came back - the ! is a negative - then show the failure view. Else $data['images'] came back, and it will be passed to the view. note i have not had to use $this-> for anything and it won't be needed in the view.
Would also suggest using separate methods - have one method to show all images and a separate method like returnimage($id) to show an image based on a specific validated $id.
====== Edit
You can access as many models as you want and pass that data to the View. You have a different issue - the problem is that you are waiting until the View to find out - and then it makes it more difficult to figure out what is wrong.
Look at this page and make sure you understand the differences between query results
http://ellislab.com/codeigniter/user-guide/database/results.html
When you have problems like this the first thing to do is make a simple view, and echo out directly from the model method that is giving you problems. Its probably something very simple but you are having to look through so much code that its difficult to discover.
The next thing is that for every method you write, you need to ask yourself 'what if it doesn't return anything?' and then deal with those conditions as part of your code. Always validate any input coming in to your methods (even links) and always have fallbacks for any method connecting to a database.
On your view do a var_dump($get_with_images) The error being given is that you are trying to use/access $get_with_images as an object but it is not an object.
or better yet on your controller do a
echo '<pre>';
var_dump($this->page_m->get_no_parents());
exit();
maybe your model is not returning anything or is returning something but the data is not an object , maybe an array of object that you still need to loop through in some cases.

cakephp invalidate element array

I am using cakephp. I have a form with an element array.
For ex:-
<textarea name="data[User][0][description]>
<textarea name="data[User][1][description]>
From the controller, I need to invalidate (manually) the array field if it is empty and need to show errors to the respective field.
What is the correct syntax for invalidating the field if it an element array ?
I know, the following will work for single element . How it will be for an element array ?
$this->User->invalidate("description");
Unfortunately you cannot invalidate the field with that function.
But what invalidate() does?
function invalidate($field, $value = true) {
if (!is_array($this->validationErrors)) {
$this->validationErrors = array();
}
$this->validationErrors[$field] = $value;
}
It just set validationErrors of the model.
So, you can do following in your Controller (but I also appeal you to move that validation in the Model):
$this->User->validationErrors[1]['description'] = 'Your error message';
The following code will invalidate the second description in the list.
HTH
You can type in view:
<?php
echo $this->Form->error("User.1.description");
?>
Thanks Nik,
your answer helped me, but halfway, because my problem was with a compound field by other subfields.
account_number {
bank_code,
bank_office,
check_digit,
account
}
In this case if we need put in validation error in one subfield, this is the solution:
$this->Model->validationErrors['account_number']['bank_code'][0] = 'Your message error';
I hope this help someone.
Regards.
I had similar problem, since it was for admin panel I showed error message on the first level of field i.e. for this portion only.
If you are validation on controller, just create an array of error with field name and error message, set it in controller and display message if in_array($field, $withErrorArray) in view.

Resources