passing variable from controller to view with CodeIgniter - codeigniter

I'm trying to structure my controllers in several small functions and I'm struggling with the following code:
building controller:
public function index(){
$data['title'] = 'my title part 1';
$data['title'] .= 'my title part 2';
$data = $this->function1();
$data = $this->function2();
$data['end'] .= 'end of this block';
$data['main_content'] = 'buildingView';
$this->load->view('templates/default',$data);
}
public function1(){
$data['block1'] = 'test1';
$data['blockA'] = 'testA';
$data['blockB'] = 'testB';
$data['blockC'] = 'testC';
return $data;
}
public function2(){
$data['block2'] = 'test2';
$data['block3'] = 'test3';
$data['block4'] = 'test4';
$data['block5'] = 'test5';
return $data;
}
buildingView
echo $title;
echo $block1;
echo $block2;
echo $end;
The problem is that the $data variable from function2 overwrites the one from from function1.
How can I pass the data generated from within Index and both functions?
I've tried the code below but it doesn't work either:
$data[] = $this->function1();
$data[] = $this->function2();
EDIT: I edited functions 1 & 2 because they actually return an array of several variables.

You are overriding $data variable. So for your condition use array_merge() and keep it on top in $data variable. Like below
public function index(){
$data1 = $this->function1();
$data2 = $this->function2();
$data = array_merge($data1,$data2);
$data['title'] = 'my title part 1';
$data['title2'] .= 'my title part 2';
$data['end'] .= 'end of this block';
$data['main_content'] = 'buildingView';
$this->load->view('templates/default',$data);
}
public function1(){
$data['block1'] = 'test1';
$data['blockA'] = 'testA';
$data['blockB'] = 'testB';
$data['blockC'] = 'testC';
return $data;
}
public function2(){
$data['block2'] = 'test2';
$data['block3'] = 'test3';
$data['block4'] = 'test4';
$data['block5'] = 'test5';
return $data;
}

public function index()
{
$data['title'] = 'my title part 1';
$data['title'] .= 'my title part 2';
$data['block1'] = $this->function1();
$data['block2'] = $this->function2();
$data['end'] .= 'end of this block';
$data['main_content'] = 'buildingView';
$this->load->view('templates/default',$data);
}
The results of your functions will be accessed in the view with the vars $block1 and $block2.
These definitions work better for demonstration purposes
public function function1()
{
return 'test1';
}
public function function2()
{
return 'test2';
}
With the helper function defined as in your question's code
public function function1(){
$data['block1'] = 'test1';
return $data;
}
And assigning the return to a var that is then passed to the view
$data['func1'] = $this->function1();
$this->load->view('templates/default',$data);
In the view do this to show the result
echo $func1['block1'];
It is very common and perfectly acceptable to pass arrays to views.
public function function2(){
$data['block1'] = 'test2';
$data['block2'] = 'test3';
$data['block3'] = 'test4';
$data['block4'] = 'test5';
return $data;
}
Passed to the view
$data['func2'] = $this->function2();
$this->load->view('templates/default',$data);
Accessed in the view. This time using an iterator to display each item
in the array.
foreach($func2 as $item)
{
echo $item."<br>";
}
Or get each item one at a time
echo $func2['block1']."<br>";
echo $func2['block2']."<br>";
echo $func2['block3']."<br>";
echo $func2['block4']."<br>";
You can pass object instances to a view too. This version of function2() returns an object instance.
public function function2()
{
$data = new stdClass();
$data->block1 = 'test2';
$data->block2 = 'test3';
$data->block3 = 'test4';
$data->block4 = 'test5';
return $data;
}
Assign the function return to an array that's passed to a view
$data['obj2'] = $this->function2();
$this->load->view('templates/default',$data);
Using it in the view
echo $obj2->block1;
echo $obj2->block2;
...
Iterators (foreach) works on object instances too.

Related

Too few arguments to function App\Awe\JsonUtility::addNewProduct(),

i am trying to create a CRUD app and am having trouble, if anyone can point me in the right direction i would be grateful, thank you.
Hi there i am having difficulty using data from the json.
i have used it here and it as worked
class JsonUtility
{
public static function makeProductArray(string $file) {
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product) {
switch($product['type']) {
case "cd":
$cdproduct = new CdProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['playlength']);
$products[] = $cdproduct;
break;
case "book":
$bookproduct = new BookProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['numpages']);
$products[]=$bookproduct;
break;
}
}
return $products;
}
this is my controller
public function index()
{
// create a list.
$products = JsonUtility::makeProductArray('products.json');
return view('products', ['products'=>$products]);
}
this is my route
Route::get('/product' , [ProductController::class, 'index'] );
how can i use this on my controller and what route should i set up to create a product
public static function addNewProduct(string $file, string $producttype, string $title, string $fname, string $sname, float $price, int $pages)
{
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product) {
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $producttype;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($producttype=='cd') $newProduct['playlength'] = $pages;
if($producttype=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents($file, $json))
return true;
else
return false;
}
This is where i am trying to type to code into.
public function create()
{
//show a view to create a new resource
$products = JsonUtility::addNewProduct('products.json');
return view('products', ['products'=>$newProduct], );
}
your function addNewProduct() is expecting 7 parameters when called.
you are getting this error because you cannot provide those parameters that your function is looking for.
in your code above you are passing 'products.json' which is in a string format.
lets assume that it is a JSON data. it will still fail because you are only passing 1 parameter to a function that is expecting 7 parameters.
what you could probably do is change it to
public static function addNewProduct($data)
{
// code here
}
then you can pass your JSON data and then go through each of your json using a loop.

Codeigniter3.x calling multiple stored procedure cache

This is somewhat related to [CodeIgniter active records' problems calling multiple stored procedures
but I am not experiencing a blank page; instead when I am passing my data array to view it seems that the the preceding array also being drag to the view.
model
public function data1($student) {
$year = 1;
$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql, array($course, $student, $year, $sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
public function data2($student) {
$year = 1;
$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
} else {
mysqli_next_result( $this->db->conn_id );
return $query->result();
}
}
Controller:
$data['data1']=data1 from my model(SP);
$data['data2']=data2 from my model(SP);
View:
foreach($data2 as key => $value ) {
echo ....;
}
Here's the PROBLEM... in the view, I only wanted to output the $data2 but to my surprise $data1 is also being output.
Does anybody else have this issue?
I JUST SOLVE IT.
Model
public function data1($student){
**$this->db->initialize();**
$year = 1;$sem = 1;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
public function data2($student){
**$this->db->initialize();**
$year = 1;$sem = 2;
$course = $this->getStudentCourseByStudentId($student);
$sql = "CALL EVALUATION_BY_YEAR_SEM(?,?,?,?)";
$query = $this->db->query($sql,array($course,$student,$year,$sem));
if (!$query) {
return $this->db->error();
}else {
mysqli_next_result( $this->db->conn_id );
return $query->result();**$this->db->close();**
}
}
controller
$data['data1']=data1 from my model(SP);
**$this->db->close();**
$data['data2']=data2 from my model(SP);

Getting Error when converting array to a variable in laravel

I have problem when converting multiple checkbox($request->courses) to a variable(checkbox1).Because I need to insert an array to Database.
public function store(Request $request) {
$customer = new prospect;
$customer->ProspectName = $request->ProspectName;
$customer->NicNumber = $request->NicNumber;
$customer->ContactNumber = $request->ContactNumber;
$customer->ContactAddress = $request->ContactAddress;
$customer->Comments = $request->Comments;
$customer->ReferredThrough = $request->ReferredThrough;
$checkbox1 = $request->courses; //courses is an array from form
$chk = "";
foreach ($checkbox1 as $chk1) {
$chk .= $chk1 . ",";
}
$customer->IntrestedCourses = $chk;
if ($customer->save()) {
echo 'saved successfully';
} else {
echo 'error';
}
}
But I'm getting error!

Codeigniter-passing value from controller to model

My English is not good so sorry for any mistake. I'm new to Codeigniter, I am trying to search record by using this code, this is my controller code:
public function search() {
if(isset($_POST['search']))
{
$s = $_POST['search'];
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name =' ,"{$s}" );
$query = $this->db->get();
$res = $query->result();
$data['user'] = null ;
if($res)
{
$data['user'] = $res ;
}
$this->load->view('filter' , $data);
}
}
It is working fine but I want to write this code in separate Model.
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name =' ,"{$s}" );
$query = $this->db->get();
$res = $query->result();
But i don't know how to pass this variable value $s = $_POST['search']; to my model. Any suggestion?
you can try the following
//in your application/models Folder put a File called UserSearch_Model.php
class UserSearch_Model extends CI_Model
{
public function search($strSearch)
{
$query = $this->db
->select('u_id,name,email,phone')
->from('user')
->where('name' ,$s)
->get();
return $query->result();
}
}
//and in your controller
public function search()
{
$strSearch = $this->input->post('search');
if (!empty($strSearch))
{
$data = [];
$this->load->model("UserSearch_Model");
$data['user'] = $this->UserSearch_Model->search($strSearch);
if (is_array($data['user']) && count($data['user']) > 0)
{
$this->load->view('filter' , $data);
}
}
}
You can try this solution for your problem :
public function search() {
$search_value = $this->input->post('search'));
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
if (isset($search_value) && !empty($search_value)) {
$this->db->where('name',$search_value);
// OR
$this->db->like('name', $search_value);
}
$query = $this->db->get();
$res = $query->result();
$data['user'] = null;
if ($res) {
$data['user'] = $res;
}
$this->load->view('filter', $data);
}
I hope it will help.
Controller
public function search() {
$search = $this->input->post('search');
$this->load->model('your_model'); //<-- You can load the model into "__construct"
$search_result = $this->your_model->your_search_function($search); //<-- This is how you can pass a variable to the model from controller
$this->load->view('your_view',['search_result'=>$search_result]); //<-- This is how you can load the data to the view. Hear your search result array is loaded on your view
}
Model
public function your_search_function($search) {
//You will receive this search variable ^^ here in your model
$this->db->select('u_id,name,email,phone');
$this->db->from('user');
$this->db->where('name',$search);
$query = $this->db->get();
$result = $query->result_array();
if(isset($result) && !empty($result))
{
return $result;
} else
{
return FALSE;
}
}

How to pass a message from model to controller codeigniter?

I want to pass a message variable in some conditions to controller from model in codeigniter. But when i am doing this it is printing only "No" everytime.
Model is
public function add_city() {
/* Storing form data into an array */
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
And Controller is
public function addingCity() {
$this->add_model->add_city();
var_dump($msg);
//redirect("/city");
}
Try This also
public function add_city() {
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
On controller redirect message with get method -
public function addingCity() {
$msg = $this->add_model->add_city();
redirect("/city?msg=".$msg);
}
And finally print this message on view page
echo $this->input->get('msg');
You need to assign value to $msg in your controller
public function addingCity() {
$msg=$this->add_model->add_city();// assign
var_dump($msg);
//redirect("/city");
}
Try this
public function add_city() {
$city_name = $this->input->post('city');
$city_overview = $this->input->post('overview');
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='$city_name' ORDER BY id ASC");
$result = $query->result_array()
$count = count($result);
if(empty($count))
{
$msg = "No";
return $msg;
}
else{
$data = array(
'city_name'=>$this->input->post('city'),
'city_overview'=>$this->input->post('overview') );
$this->db->insert('city_tbl', $data);
$msg = "Yes";
return $msg;
}
}
In Controller
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;
}
To pass data to view
public function addingCity() {
$data['msg'] = $this->add_model->add_city();
$this->load->view("filename", $data); # ex $this->load->view("index", $data);
}
Error is in your controller function
Try with this code
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;die;
//redirect("/city");
}

Resources