Codeigniter Displaying Information In A View? - mysql

I'm extracting two different sets of data from a function in my model (syntax below). I'm trying to display the data my view. I put the variable in var_dump and var_dump is displaying the requested information but I'm having a hard time accessing that information. I'm getting two different sets of error messages as well. They are below. How would I display the information in my view? Thanks everyone.
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);
}
Model_data
function getJoinInformation($year,$make,$model)
{
$data['getPrice'] = $this->getPrice($year,$make,$model);
$data['getOtherPrice'] = $this->getOtherPrice($year,$make,$model);
return $data;
}
function getPrice($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();
}
function getOtherPrice($year,$make,$model)
{
$this->db->select('*');
$this->db->from('tbl_car_description d');
$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();
}
View
<?php
var_dump($allvehicledata).'<br>';
//print_r($allvehicledata);
if(isset($allvehicledata) && !is_null($allvehicledata))
{
echo "Cities of " . $allvehicledata->cardescription_id . "<br />";
$id = $allvehicledata['getPrice']->id;
$model = $allvehicledata[0]->model;
$make = $allvehicledata->make;
echo "$id".'<br>';
echo "$make".'<br>';
echo "$model".'<br>';
echo $allvehicledata->year;
}
?>
Error Messages
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: views/view_show_all_averages.php
Line Number: 7
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: views/view_show_all_averages.php
Line Number: 9

In your controller you are assigning the result of function getJoinInformation to the variable allvehicledata. This variable is then assigned to the view.
The function getJoinInformation is returning an array with the following
$data = array(
'getPrice' => $this->getPrice($year,$make,$model),
'getOtherPrice' => $this->getOtherPrice($year,$make,$model)
);
So in your view you can access the attributes getPrice and getOtherPrice in the object $allvehicledata like
$allvehicledata->getPrice;
$allvehicledata->getOtherPrice;
In line 7 you try to access the attribute cardescription_id, which is not an attribute of the object $allvehicledata.
I think this is an attribute which is get from the db query, so you should try to access it allvehicledata->getPrice->cardescription_id or allvehicledata->getOtherPrice->cardescription_id.
In line 9 you try to access some data stored in an array $model = $allvehicledata[0]->model;, but $allvehicledata is not an array.

Related

Ajax format after submit - Laravel

I'm working on project, I faced some problems
If I fill all fields and then submit there is no problem and it saved to database, but my issue if some field is empty the validation messages error appear in another page as JSON format.
I don't use any AJAX code in my view file.
Here is controller code:
public function store(RegisterRequest $request){
$user = User::create($request->all());
$user->password = Hash::make($request['password']);
if ($request->file('avatar')) {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
} else {
$path = $user->avatar;
}
$user->avatar = $path;
$user->save();
return redirect()->route('admin.user.index')->with('message','User created successfully');
And here is RegisterRequest code:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed',
'country_code' => 'sometimes|required',
'phone'=>Rule::unique('users','phone')->where(function ($query) {
$query->where('country_code', Request::get('country_code'));
})
];
Can you help me please?
Your errors should be accessible inside blade file with $errors variable which you need to iterate and display the errors.
Link to doc which will help you with the render part - https://laravel.com/docs/7.x/validation#quick-displaying-the-validation-errors
Clearly from doc as well
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
https://laravel.com/docs/7.x/validation#creating-form-requests
Also refactor the code a bit as following to run only one query to create a user instead of creating and then updating.
public function store(RegisterRequest $request){
if ($request->hasFile('avatar')) {
//use try catch for image conversion might be a rare case of lib failure
try {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
$request->avatar = $path;
} catch(\Exception $e){
//handle skip or report error as per your case
}
}
$request['password'] = Hash::make($request['password']);
$user = User::create($request->all());
return redirect()->route('admin.user.index')->with('message','User created successfully');
}

Using AJAX returned JSON encoded data in Codeigniter

I am relatively new to codeigniter. While I was trying to perform a searching operation on my data base using AJAX, The code is returned as successful and the data is retrieved but, This data is JSON encoded and is in the javascript portion of my view so I am unable to use the json_decode function of codeigniter
public function lookup(){
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
echo json_encode($data); //echo json string
}
the data is accessed in the javascript as data.message.
Please tell me is there anyway i can use this data in the php part of my program
<?php
class MAutocomplete extends CI_Model{
function lookup($keyword){
$this->load->database();
$this->db->select('*');
$this->db->from('Students');
$this->db->like('firstName',$keyword,'after');
$query = $this->db->get();
// echo '<pre>'; print_r($query->result()); exit;
return $query->result();
}
}
I think you need to parse json response in Ajax's success function using JSON.parse().Like this..
$.ajax({
url:'',//your url
dataType:'JSON',
data:'',//your data
success:function(response){
data = JSON.parse(response);
alert(data.message.value);//alerts value
}
});
In controller use count rather than empty.To check the array
if( count($query) >0 )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
You should use to response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));

simple codeigniter query + results display won't display

I'm trying to display data from my database in a Codeigniter view. Seems like it should be simple, but it's just not working.
I'm getting 2 errors: undefined variable ($movielist, in the view) and invalid argument for php foreach, also in the view.
Any idea how I can get this to work? Code below.
Controller
function displayMovies() {
$this->load->model('movie_list_model');
$data['movielist'] = $this->movie_list_model->getList();
$this->load->view('movielist_view', $data);
}
Model
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row)
{
echo $row['firstname'];
echo $row['lastname'];
echo $row['favorite_movie'];
}
}
View
<?php foreach($movielist as $mlist)
{
echo $mlist->firstname . '<br />';
echo $mlist->lastname . '<br />';
echo $mlist->favorite_movie;
}
?>
If( the query doesn't find any rows, it will return null, resulting in the undefined error in your view. The invalid argument error is because you can't iterate through null.
A safety would be including something like this in your view:
if($movielist)
{
/* foreach() {} */
}
Also, your model should only return data (not echo it).
function getList() {
$query = $this->db->query('SELECT firstname, lastname, favorite_movie FROM movies');
return $query->result(); /* returns an object */
// Alternatively:
// return $query->result_array(); /* returns an array */
}
I also recommend using Active record:
function getList() {
$this->db->select('firstname');
$this->db->select('lastname');
$this->db->select('favorite_movie');
$query = $this->get('movies');
return $query->result();
}
Good luck!

Output query to csv, codeigniter

I currently have a report that give me the users ID number and their email address, But I would like to make this in a CSV file instead of tables and rows like I currently have.
Here is my controller
function View_Email_E()
{
$data = array();
if($query = $this->report_model->View_Email_English())
{
$data['records'] = $query;
}
$data['main_content'] = 'view_all_email_english';
$this->load->view('includes/template', $data);
}
Here is my model
function View_Email_English()
{
$query = $this->db->where(array('Dial_Up' => '0', 'Language' => 'English', 'Membership_Status' => 'Active'));
$query = $this->db->like('Email', '#');
$query = $this->db->get('Membership');
return $query->result();
}
For some reason my view is not being shown in code mode, but it is an auto generated table using these this snippet of code. Each row returns ID and Email from the database.
<?php if(isset($records)) : foreach($records as $row) : ?>
How can I make a CSV file with just ID and email fields?
Thanks
I think you can use the csv_from_result function in dbutil to do it. Try something like this:
$csvContent = $this->dbutil->csv_from_result($query);
if ( ! write_file('./path/to/file.csv', $csvContent)) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
http://codeigniter.com/user_guide/database/utilities.html#csv
Add
$this->db->select(array('ID','Email'));
To your View_Email_English function.

Convert codeigniter query to json?

I want to convert a model query to json with json_encode, it doesn't work. But with a ordinary array it does.
$arr = array("one", "two", "three");
$data["json"] = json_encode($arr);
Output
<?php echo "var arr=".$json.";"; ?>
var arr=["one","two","three"];
But when I try to convert a query codeigniter throws an error. What is it with that?
This is the error message:
A PHP Error was encountered Severity:
Warning Message: [json]
(php_json_encode) type is unsupported,
encoded as null
And the converted "query" result = I mean model method is like this:
{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null}
I try to do like this
$posts = $this->Posts_model->SelectAll();
$data["posts"] = json_encode($posts);
By the way, the model and method works just fine when I do it without json_encode.
Something I'm propably doing wrong, but the question is what?
You appear to be trying to encode the CodeIgniter database result object rather than the result array. The database result object acts as a wrapper around the cursor into the result set. You should fetch the result array from the result object and then encode that.
Your model code appears to be something like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
// Return the result object
return $this->db->query($sql);
}
It should be more like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
This will return an array of objects which you can encode in JSON.
The reason you are getting an error trying to encode the result object is because it has a resource member variable that cannot be encoded in JSON. This resource variable is actually the cursor into the result set.
public function lastActivity()
{
header("Content-Type: application/json");
$this->db->select('*');
$this->db->from('table_name');
$query = $this->db->get();
return json_encode($query->result());
}
As per latest CI standard use the following code in your controller file:
$this->output->set_content_type('application/json')->set_output(json_encode($arr));
Models (Post):
function SelectAll()
{
$this->db->select('*');
$this->db->from('post');
$query = $this->db->get();
return $query;
}
Controllers :
$data['post'] = $this->post->SelectAll()->result_array();
echo json_encode($data);
Result:
{"post":[{"id":"5","name":"name_of_post"}]}
Here is the working solution:
$json_data = $this->home_model->home_getall();
$arr = array();
foreach ($json_data as $results) {
$arr[] = array(
'id' => $results->id,
'text' => $results->name
);
}
//save data mysql data in json encode format
$data['select2data'] = json_encode($arr);