Passing variables between functions in laravel - php

I guess I'm just looking over it but I can't get my variables to my view.
In the same controller I call a function, from there I return an array containing the variables (also array's). From within the function I originally started I send the variables to the view.
But, in the view I get an error saying the variable is undefined.
The information I need is in array $items and array $trans. These need to get in the function confirmation and end up in the confirmation view.
The two functions (I tried to remove most code that has nothing to do with the question):
public function confirmation($order_id){
$order = Orders::findOrFail($order_id);
if(isset($order->transaction_id)){
$data = [];
$data['order_id'] = $order->order_reference;
$data['trans'] = $order->dat['tr'];
$data['items'] = $order->dat['it'];
return view('confirmation', $data);
}else{
//Nothing relevant
}
}
public function sendpicqer($order_id){
$order = Orders::with(['orderDetails', 'orderAddress', 'customer'])->where('order_id', $order_id)->first();
$order_details = OrderDetails::where('order_id', $order_id)->get();
$error = $order_id;
$result = $this->picqer->addCustomer($customer);
if(!isset($result['data'])){
$error = $result;
if(is_array($result)){
$error = json_encode($result);
}
return redirect()->route('cancel');
}
$orderData = [
'idcustomer' => $result['data']['idcustomer']
];
$orderData['products'] = [];
$items = [];
foreach($order_details as $od){
$pid = $od->product_id;
switch ($pid) {
case 1:
$pid = 2399983;
break;
case 2:
$pid = 2399990;
break;
}
$orderData['products'][] = [
'idproduct' => $pid,
'amount' => $od->quantity
];
$items[] = [
'sku' => $pid,
'name' => $od->product_id->product_name,
'price' => $od->product_id->product_price,
'quantity' => $od->quantity
];
}
$result = $this->picqer->addOrder($orderData);
if(isset($result['data'])){
//Succeeded!
$idorder = $result['data']['idorder'];
$orderid = $result['data']['orderid'];
$trans = array('id' => $orderid, 'affiliation' => 'Matt Sleeps', 'revenue' => $order->total_price);
$dat = [];
$dat['tr'] = $trans;
$dat['it'] = $items;
return $dat;
$result2 = $this->picqer->sendRequest('/orders/'.$idorder.'/process', null, 'POST');
if(!isset($result2['data'])){
$error = $result2;
if(is_array($result2)){
$error = json_encode($result2);
}
return redirect()->route('cancel');
}
}else{
$error = $result;
if(is_array($result)){
$error = json_encode($result);
}
return redirect()->route('cancel');
}
//Order is successfully confirmed and send to Picqer!
$error = '(Both to the customer and with Picqer)';
}
This is the part of view where I need access to the variables:
<?php
var_dump($order_id);
var_dump($trans);
var_dump($items);
// Function to return the JavaScript representation of a TransactionData object.
function getTransactionJs(&$trans) {
return <<<HTML
ga('ecommerce:addTransaction', {
'id': '{$trans['id']}',
'affiliation': '{$trans['affiliation']}',
'revenue': '{$trans['revenue']}'
});
HTML;
}
// Function to return the JavaScript representation of an ItemData object.
function getItemJs(&$transId, &$item) {
return <<<HTML
ga('ecommerce:addItem', {
'id': '$transId',
'name': '{$item['name']}',
'sku' : '{$item['sku']}',
'price': '{$item['price']}',
'quantity': '{$item['quantity']}'
});
HTML;
}
?>
<script>
<?php
echo getTransactionJs($trans);
foreach ($items as &$item) {
echo getItemJs($trans['id'], $item);
}
?>
ga('ecommerce:send');
</script>

You have to send the variables to the view. You could change the code to something like this:
//Return the view via confirmation function.
public function sendpicqer($order_id){
...
return $this->confirmation($order_id, $items, $trans);
}
public function confirmation($order_id, $items, $trans){
$order = Orders::findOrFail($order_id);
if(isset($order->transaction_id)){
$data = [];
$data['order_id'] = $order->order_reference;
$data['trans'] = $trans;
$data['items'] = $items;
//Send the variables to the view
return view('confirmation', $data);
}else{
return redirect()->route('cancel');
}
}
Hope this helps...

Related

How to pass values from a assigned variable to view?

I wanted to pass some values to the view.
The $result may be 0 or 1 or '' and I tried to use this below code:
public function whatwedo($result='')
{
$result = array();
$result['status'] = $result;
$this->load->view('admin/whatwedo',$result);
}
public function add_whatwedo()
{
//$this->load->library('form_validation');
$this->form_validation->set_rules('text-input','Title','required');
if($this->form_validation->run() != true)
{
$result = 0;
$this->whatwedo($result);
}
else
{
$this->load->model('admin_model');
$result = $this->admin_model->ins_whatwedo($this->input->post());
//print_r($result);exit();
$this->whatwedo($result);
}
}
And in the view:
<?php
print_r($status);
?>
But, the $status is Array ( )
The problem is this line:
$result = array();
Because now the $result variable is an empty array so when you create the index status on result you assign it an empty array.
To fix you can do something like:
public function whatwedo($input = '')
{
$result['status'] = $input;
$this->load->view('admin/whatwedo', $result);
}
or even...
public function whatwedo($input = '')
{
$this->load->view('admin/whatwedo', ["status" => $input]);
}

How to access array values in laravel

This method i am using for storing currentTime in database using ajax call and its working
public function saveTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 404]);
}
$video = \App\Lession::where('id',$lession_id)->first();
$lesson_id = $request->lession_id;
$progress = $request->time;
//save them somewhere
$watch_history = $user->watch_history;
$watch_history_array = array();
if ($watch_history == '') {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
} else {
$founder = false;
$watch_history_array = json_decode($watch_history, true);
for ($i = 0; $i < count($watch_history_array); $i++) {
$watch_history_for_each_lesson = $watch_history_array[$i];
if ($watch_history_for_each_lesson['lession_id'] == $lesson_id) {
$watch_history_for_each_lesson['progress'] = $progress;
$watch_history_array[$i]['progress'] = $progress;
$founder = true;
}
}
if (!$founder) {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
}
}
$data['watch_history'] = json_encode($watch_history_array);
$check = User::where('id',$user->id)->update(['watch_history' => $watch_history_array]);
return response()->json(['message' => 'Time saved', 200]);//send http response as json back to the ajax call
}
But when I use this another method to get the time back for playback it's getting the array inside an array
public function getTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403]);
}
$user_video = User::where('id',$user->id)->first();
$array = $user_video->watch_history;
foreach ($array as $key => $value) {
echo $check;
}
}
My current Output in a database is as follows
[{"lession_id":"157","progress":"71.449464"},{"lession_id":"156","progress":"92.113123"}]
So help me to get the values out of that for each lession id

React Js .json() leaves out some data that are available from the api

I am working on a project that gets an array of integers from the api and prints them on the screen. The problem here is, POSTMAN shows that there is data in json format with no errors as shown in the figure but react js says there's no data.
The api code, the sizes in $attributes are there just to see that react takes those but doesn't take others that come form the database (Click To See the code)
This is the api code.
public function __construct()
{
$this->load->database();
}
public function getAllProducts()
{
$query = $this->db->get('products');
return $query->result_array();
}
private function cutifyProduct($productResult,$isSingle=false){
foreach($productResult as $key => $product){
$productId = $product['id'];
$mediaQuery = $this->db->get_where('media',array('productId'=>$productId));
$categoryQuery = $this->db->get_where('categories',array('id'=>$product['categoryId']));
$thisProductCategory = $categoryQuery->result_array()[0];
$productResult[$key]['categoryTitle'] = $thisProductCategory['name'];
if($isSingle){
//for breadcrumb
$breadcrumb = [];
$breadcrumb[] = $thisProductCategory;
while($thisProductCategory['parentId']!=0){
$categoryQuery = $this->db->get_where('categories',array('id'=>$thisProductCategory['parentId']));
$thisProductCategory = $categoryQuery->result_array()[0];
$breadcrumb[] = $thisProductCategory;
};
$productResult[$key]['breadcrumb'] = $breadcrumb;
//for product attributes
$attributes = [];
$tempSizeAttribute = array();
$tempColorAttribute = [];
$tempStorageAttribute = [];
$tempRamAttribute = [];
$attributesQuery = $this->db->get_where('attributes',array('productId'=>$productId));
$thisProductAttributes = $attributesQuery->result_array();
$attributes['size'] = array(
"sizeType"=>"UK",
"sizes"=>array(1,2,3),
);
foreach($thisProductAttributes as $productAttribute){
if($productAttribute['title']=="size"){
//$attributes['size']['sizes'][] = (int) $productAttribute['name'];
$tempSizeAttribute[]=(int) $productAttribute['name'];
}elseif($productAttribute['title']=="color"){
$tempColorAttribute[] = array(
"productId"=>explode("|",$productAttribute['name'])[0],
"name"=>explode("|",$productAttribute['name'])[1],
);
}
}
$attributes['size']['sizes'] =array_merge($attributes['size']['sizes'],$tempSizeAttribute);
$productResult[$key]['attributes'] = $attributes;
//for vendor information
$vendorInfo = [];
$vendorQuery = $this->db->get_where('vendors',array('id'=>$product['vendorId']));
$vendorResult = $vendorQuery->result_array();
$productResult[$key]['vendorDetails'] = $vendorResult;
}
$productResult[$key]['media'] = $mediaQuery->result_array();
$productResult[$key]['link'] = "/product/".$productResult[$key]['slug'];
if($productResult[$key]['discountPercent']=="0.00" || $productResult[$key]['discountPercent']==0 || $productResult[$key]['discountPercent']=="0" || $productResult[$key]['discountPercent']=="0.0"){
$productResult[$key]['price'] = array(
"current"=> $productResult[$key]['price'],
);
}else{
$productResult[$key]['price'] = array(
"current"=> $productResult[$key]['price'] - (($productResult[$key]['discountPercent']*$productResult[$key]['price'])/100),
"previous"=> $productResult[$key]['price'],
);
}
foreach($productResult[$key]['media'] as $mediaKey => $media){
if($isSingle){
if($media['isPrimary']=="1" || $media['isPrimary']==1 ){
if(substr( $media['url'], 0, 4 ) != "http"){
$productResult[$key]['image']= "https://admin.ratomatoshop.com/media/medium/".$media['url'];
}
}
if(substr( $media['url'], 0, 4 ) != "http"){
$productResult[$key]['images']['medium'][]= "https://admin.ratomatoshop.com/media/medium/".$media['url'];
$productResult[$key]['images']['original'][]= "https://admin.ratomatoshop.com/media/original/".$media['url'];
}else{
$productResult[$key]['images']['original'][]=$media['url'];
}
}else{
if($media['isPrimary']=="1" || $media['isPrimary']==1 ){
if(substr( $media['url'], 0, 4 ) != "http"){
$productResult[$key]['image']= "https://admin.ratomatoshop.com/media/small/".$media['url'];
}
}
}
}
}
return $productResult;
}
public function getLatestProducts($noOfProducts)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('products');
$productResult = $query->result_array();
return $this->cutifyProduct($productResult);
}
public function getOnSaleProducts($noOfProducts)
{
$this->db->order_by('discountPercent', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('products');
$productResult = $query->result_array();
return $this->cutifyProduct($productResult);
}
public function getTopRatedProducts($noOfProducts)
{
$this->db->order_by('rating', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('products');
$productResult = $query->result_array();
return $this->cutifyProduct($productResult);
}
public function getProductData($productSlug)
{
$query = $this->db->get_where('products',array('slug'=>$productSlug));
$productResult = $query->result_array();
return $this->cutifyProduct($productResult,true);
}
public function getFeaturedProducts($noOfProducts)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('featuredproducts');
$results = $query->result_array();
$products = [];
foreach($results as $result ){
$products[] = $this->getWhere('id',$result['productId']);
}
return $this->cutifyProduct($products);
}
public function getSpecialProducts($noOfProducts)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($noOfProducts);
$query = $this->db->get('specialproducts');
$results = $query->result_array();
$products = [];
foreach($results as $result ){
$product = $this->getWhere('id',$result['productId'])[0];
$product['dateEnd'] = $result['dateEnd'];
$product['discountPercent'] = $result['discountPercent'];
$products[] = $product;
}
return $this->cutifyProduct($products);
}
public function newProduct($productData)
{
return $this->db->insert('products',$productData);
}
public function isProduct($productId){
$product = $this->getWhere('id',$productId);
if($product!=null && is_array($product) && count($product)>0){
return true;
}else{
return false;
}
}
public function getWhere($key,$value){
$query = $this->db->get_where('products',array($key=>$value));
return $query->result_array();
}
}
The postman response from the api (Click To See the code)
This is the post man response
"attributes": {
"size": {
"sizeType": "UK",
"sizes": [
1,
2,
3,
36,
37,
38,
39,
40
]
}
},
The json data that react gets. (Click To See the code)
This is the react's console log:
"attributes": {
"size": {
"sizeType": "UK",
"sizes": [
1,
2,
3,
]
}
},

PHP CODEIGNITER UPDATE issue

I can't update data in a record in CodeIgniter .
I have posted the code below:-
//CONTROLLER
//RESERVATION.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reservation extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reservation_model','reservation');
}
public function index()
{
$this->load->helper('url');
$this->load->view('manage_reservation');
}
public function reservationview()
{
$this->load->helper('url');
$this->load->view('view_reservation');
}
public function ajax_list()
{
$list = $this->reservation->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $reservation) {
$no++;
$row = array();
$row[] = $reservation->id;
$row[] = $reservation->dateReserved;
$row[] = $reservation->requestedBy;
$row[] = $reservation->facility;
$row[] = $reservation->dateFrom;
$row[] = $reservation->dateTo;
$row[] = $reservation->timeStart;
$row[] = $reservation->timeEnd;
$row[] = $reservation->status;
$row[] = $reservation->items;
$row[] = $reservation->purpose;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-trash"></i></a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->reservation->count_all(),
"recordsFiltered" => $this->reservation->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->reservation->get_by_id($id);
$data->dateFrom = ($data->dateFrom == '0000-00-00') ? '' : $data->dateFrom;
$data->dateTo = ($data->dateTo == '0000-00-00') ? '' : $data->dateTo; // if 0000-00-00 set tu empty for datepicker compatibility
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$insert = $this->reservation->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$this->reservation->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->reservation->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('requestedBy') == '')
{
$data['inputerror'][] = 'requestedBy';
$data['error_string'][] = 'Requested Name is required*';
$data['status'] = FALSE;
}
if($this->input->post('dateFrom') == '')
{
$data['inputerror'][] = 'dateFrom';
$data['error_string'][] = 'Please Select a Date*';
$data['status'] = FALSE;
}
if($this->input->post('dateTo') == '')
{
$data['inputerror'][] = 'dateTo';
$data['error_string'][] = 'Please Select a Date*';
$data['status'] = FALSE;
}
if($this->input->post('timeStart') == '')
{
$data['inputerror'][] = 'timeStart';
$data['error_string'][] = 'Please select a Time*';
$data['status'] = FALSE;
}
if($this->input->post('timeEnd') == '')
{
$data['inputerror'][] = 'timeEnd';
$data['error_string'][] = 'Please select a Time*';
$data['status'] = FALSE;
}
if($this->input->post('status') == '')
{
$data['inputerror'][] = 'status';
$data['error_string'][] = 'Please Indicate Status*';
$data['status'] = FALSE;
}
if($this->input->post('items') == '')
{
$data['inputerror'][] = 'items';
$data['error_string'][] = 'Please select an Item*';
$data['status'] = FALSE;
}
if($this->input->post('purpose') == '')
{
$data['inputerror'][] = 'purpose';
$data['error_string'][] = 'Please indicate a Purpose*';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
//MODEL
//Reservation_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reservation_model extends CI_Model {
var $table = 'tblreservation';
var $column_order = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose',null); //set column field database for datatable orderable
var $column_search = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose'); //set column field database for datatable searchable just firstname , lastname , address are searchable
var $order = array('id' => 'desc'); // default order
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
}
VIEW = manage_reservation.php = save function
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('reservation/ajax_add')?>";
} else {
url = "<?php echo site_url('reservation/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
NEWBIE TO CODE IGNITER any help will be appreciated :)
try
public function update($where, $data){
$this->db->where($where);
$this->db->set($data); //array of new data
$this->db->update($this->table);
return $this->db->affected_rows();
}
Please print your query after the update statement, this will help you to know whether you query is correct or not.
$this->db->last_query();
Please check that query in model
Controller :
$update_id = array();
$update_id['id'] = $this->input->post('id');
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$result = $this->reservation->update('table_name',$update_id, $data);
Model :
$this->db->where($where);
$this->db->update($table, $data);
return $this->db->affected_rows();

How to get rid of unused $_GET parameters in URL with Codeigniter?

I am designing search functionality with some data with Codeigniter.
My search model looks like:
class Search_Model extends CI_Model {
public function get_results($search_terms = false) {
// Build query
foreach ($search_terms as $field => $value) {
$this->db->like("{$field}", $value);
}
// Execute query
$query = $this->db->get('exams');
// Return results
return $query->result_array();
}
}
And the search controller method looks like this:
public function results() {
$search_terms = array(
'first_name' => $this->input->get('first_name', TRUE),
'last_name' => $this->input->get('last_name', TRUE),
'exam_name' => $this->input->get("exam_name", TRUE)
);
$data['title'] = "Search Results";
$data['exams'] = $this->search_model->get_results($search_terms);
$this->load->view('templates/header.php', $data);
$this->load->view('exams/index.php', $data);
$this->load->view('templates/footer.php');
}
The search is working as it should but I want to clean up the URL which comes out something like this if I only search for "First Name":
search/results?first_name=tim&last_name=&exam_name=
How can I remove those extra parameters that are unused in the URL?
The quickest way is just to filter the $searh_terms array before passing it to the model.
$search_terms = array(
'first_name' => $this->input->get('first_name', TRUE),
'last_name' => $this->input->get('last_name', TRUE),
'exam_name' => $this->input->get("exam_name", TRUE)
);
// Remove empty search values
foreach ($search_terms as $key => $value) {
if (strlen($value) == 0) {
unset($search_terms[$key]);
}
}
include jquery in your header. then add this script.
<script>
$(document).ready(function(){
$('#myform').submit(function(event){
event.preventDefault();
var url = $(this).attr('action')+'?';
var first = false;
var second = false;
if($('input[name="first_name"]').val()){
url += 'first_name='+$('input[name="first_name"]').val();
first = true;
}
if($('input[name="last_name"]').val()){
if(first){
url += '&';
}
url += 'last_name='+$('input[name="last_name"]').val();
second = true;
}
if($('input[name="exam_name"]').val()){
if(second){
url += '&';
}
url += 'exam_name='+$('input[name="exam_name"]').val();
}
window.location.replace(url);
});
});
</script>
(i didnt ran this script yet, so let me know if u get any syntax error or somethign else.)
and finally change your results function to this,
public function results() {
$search_terms = array();
if(isset($_GET['first_name'])){
$search_terms['first_name'] = $this->input->get('first_name', TRUE);
}
if(isset($_GET['last_name'])){
$search_terms['last_name'] = $this->input->get('last_name', TRUE);
}
if(isset($_GET['exam_name'])){
$search_terms['exam_name'] = $this->input->get('exam_name', TRUE);
}
$data['title'] = "Search Results";
$data['exams'] = $this->search_model->get_results($search_terms);
$this->load->view('templates/header.php', $data);
$this->load->view('exams/index.php', $data);
$this->load->view('templates/footer.php');
}
You can try this:
$mode = array();
if(isset($_GET['first_name'])):
$mode[] = 'first_name='.$_GET['first_name'];
endif;
if(isset($_GET['last_name'])):
$mode[] = 'last_name='.$_GET['last_name'];
endif;
if(isset($_GET['exam_name'])):
$mode[] = 'exam_name='.$_GET['exam_name'];
endif;
//etc...
//Then reformulate link
if(!empty($mode)){
$link = '?' . implode('&',$mode);
}else{
$link = '';
}
redirect("form.php".$link);
just filter what you send...
foreach ($search_terms as $field => $value) {
if ($value <> ""){ //or the test you like to use...
$this->db->like("{$field}", $value);
}
}

Categories