How to implement search form in codeigniter - php

I have asked this question before but i did not get the right answer. I have a table 'cv', i want to search for items in the database using two fields i.e. course and location, the two items are on the same table('cv'). I dont have an idea on how to implement the two searches.
The code below is for displaying search for course only and its working fine. Help me to use the two search criterions i.e.course and location or in other words how do i add the search for location input in my code.
Controller
function search_worker()
{
$data['query']=$this->kint_model->search_workers($this->input->post('search'));
$this->load->view('hire_display',$data);
}
Model
function search_workers($search)
{
return $query = $this->db->get_where('cv', array('course '=> $search))->result();
}
View
$data = array('name'=>'search', 'id'=>'search','value'=>'bcom');
echo form_input($data);
$data = array('name'=>'submit', 'id'=>'submit', 'value'=>'Search Item(s)');
echo form_submit($data);

Maybe you need a like clause in your query,
function search_workers($search){
//return $query = $this->db->get_where('cv', array('course '=> $search))->result();
return $this->db->like('course', $search)->like('location', $location)->get('cv')->result();
}
You should also get some basic SQL training.

Related

Laravel/Lumen API print array of records

Is it possible to make an API which prints database records like this: http://localhost:8000/products/?compare=1-2-N...(1,2,N) product id's. I have succeeded printing only one record. My route:
$router->get('products/{id}','ProductController#getProduct');
and my controller:
public function getProduct($id){
$tlt_products = DB::table('tlt_products')->find($id);
$tlt_products_features_id = DB::table('tlt_product_features')->where('product_id', $id)->get()->pluck('feature_id');
$tlt_features = DB::table('tlt_features')->whereIn('id', $tlt_products_features_id)->get()->groupBy('feature_group');
$tlt_feature_groups = DB::table('tlt_features')->groupBy('feature_group')->get()->toArray();
return response()->json([
'product' => $tlt_products,
'product_features' => $tlt_features,
'feature_groups' => $tlt_feature_groups
]);
}
could you please help me printing array of records using route like this:
http://localhost:8000/products/?compare=1-2-3...-N
Yes, it can be possible. You can try to pass a pattern through get and parse it to retrieve the information your need, but why don't you use a simple way to do that such as:
$router->get('products/{begin}/{end}','ProductController#getProduct');
every thing you want it possible just design it well and in your controller, you have
public function getProduct($begin,$end){
...
}
I finally managed to solve this issue using $tail = $request->tail;method and adding requested id like this on my form action
#php
$tail = basename(request()->path());
$text = (string)$tail;
#endphp
<form action="/product-compare/{{$text}}-{{ $product['id'] }}" method="post">

How to select from mysql array text and compare

I am collecting user selected "text" as array in mysql using PDO connection from php form there are let suppose 3 check boxes with names
1- Apple
2- Banana
3- Cherry
In DB stored values are as per shown
apple,banana,cherry
What i want : I want to display "Apple" users in certain "/offer.php" page
while i am using SELECT query and it's not working i am using pure php mvc framwork.
In Controller i done this
public function offer(){
$this->view->title = User Selection;
$this->view->offerUser = $this->model->offerUser();
$this->view->render('dashboard/offer');
}
In Model I done this
public function offerUser()
{
return $this->db->select('SELECT * FROM users WHERE selection = apple ORDER BY points DESC ');
}
In View i done this
<?php
foreach($this->offerUser as $key => $value) {?>
<tbody>
<tr>
<td></td>
<td><strong><?php echo $value['selection']?></strong></td>
</tr>
The issue is i am not able to select "Text" from stored array with model and even not able to display selection in "View" user end page.
This code format was working fine with single numeric digit selection or compare but failed with text array.
Please help me out with this i really appreciate this i am new with text array fetching.
Hope someone answer my question soon....
Regards,
james
query is not working : use single quotation around apple
public function offerUser()
{
return $this->db->select("SELECT * FROM users WHERE selection = 'apple' ORDER BY points DESC ");
}

cakePHP pagination and passedArgs

I am trying to build in a "search" box on a results page in my cakephp app. The page uses the cakePHP pagination component to show and "page" results. This is perfect, but I am having difficulties to get the next part to work.
The desired outcome:
A cakephp form (post) with an input box and a couple of select boxes, including a date selector so that I can select between dates. The user should be able to populate these fields and submit
On submit, the user selection should change the cakePHP pagination conditions in the controller
In the view I want the pagination bar to keep record of the user selection, so that when I filter through different pages, it keeps the users search. I understand this can be achieved using $this->passedArgs, hence why I am using post and not get.
The code:
// Form:
<?php
echo $this->Form->create('search', array('class' => false));
echo $this->Form->input('searchFor');
echo $this->Form->input('dateFrom');
echo $this->Form->input('dateTo');
echo $this->Form->end();
?>
// Controller:
if($this->request->is("post")) {
$filters = $this->request->data["search"];
$this->passedArgs["searchFor"] = $filters["searchFor"];
$this->passedArgs["dateFrom"] = $filters["dateFrom"]." 00:00:00";
$this->passedArgs["dateTo"] = $filters["dateTo"]." 00:00:00";
// Assign search parameters:
if($this->passedArgs["searchFor"] != "") {
$conditions["Model.field LIKE"] = "%".$this->passedArgs["searchFor"]."%";
}
$conditions["Model.created >="] = $this->passedArgs["dateFrom"];
$conditions["Model.created <="] = $this->passedArgs["dateTo"];
} else {
$conditions = array("Result.status_id >=" => 12);
}
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Result.created ASC'),
'limit' => 20
);
$this->set("results",$this->paginate("Model");
// The view file:
<?php
$this->Paginator->options(array('url' => $this->passedArgs));
?>
Where I am now:
The initial page loads with all of the results
When I populate the search boxes it does return my results
The problem:
I am convinced the way I am doing it is incorrect as I now need to do 2 checks, a) being if results has been posted and b) check if there is passedArgs available. I am 100% convinced this is not the right way of doing it.
Let's say I have 2 free form fields for search, say name and surname, if I leave surname blank my url would be written as below, and this does not look or appear to be correct. That means I have to assign default values to ensure the items below does not happen, which does not appear to be very dynamic.
http://localhost/site/controller/action/surname:0/name:John/date:0/
On refresh it says the page does not exist because the posted values is not available anylonger.
usually I proceed like this in the controller:
//transform POST into GET
if($this->request->is("post")) {
$url = array('action'=>'index');
$filters = array();
if(isset($this->data['searchFor']) && $this->data['searchFor']){
//maybe clean up user input here??? or urlencode??
$filters['searchFor'] = $this->data['searchFor'];
}
//redirect user to the index page including the selected filters
$this->redirect(array_merge($url,$filters));
}
$conditions = array();
//check filters on passedArgs
if(isset($this->passedArgs["searchFor"])){
$conditions["Model.field LIKE"] = "%".$this->passedArgs["searchFor"]."%";
}
//paginate as normal
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Result.created ASC'),
'limit' => 20
);
The idea is to transform the POST sent by your form into GET. so you wont have problems with the paginator nor the refresh
Hope this helps
What you want can be done a lot more simple and DRY by using this search plugin.
It automates what you want more or less plus it already can do more than your code.
So I suggest you to use the plugin directly or take a look at it how it does the trick. :)

how do I exclude table field MYSQL

Sorry about the strange title, but I am having a small issue if the user type is 2 or 3 then I need the user not to be able to insert or update a few fields, but instead of creating a number of insert queries listed below are a few fields I need not updated.
AMStatus,HQStatus,approvedforsite
public function databaseinsert($data)
{
$this->data = $data;
switch($this->data['action']){
case "newlead":
$this->insert("customer_detail",
"TradingName,Street,City,State,PostCode,Industry,SubCategories,Membership,LeadStatus,AMStatus,HQStatus,approvedforsite,Salutation,FirstName,LastName,Website,Company,ABN_ACNNumber,Phone,Mobile,Notes,Description",
"'{$this->data['tradingname']}',
'{$this->data['street']}',
'{$this->data['suburb']}',
'{$this->data['state']}',
'{$this->data['postcode']}',
'{$this->data['category']}',
'{$this->data['subcategory']}',
'{$this->data['membership']}',
'{$this->data['salestatus']}',
'{$this->data['managerstatus']}',
'{$this->data['hqstatus']}',
'{$this->data['publishtoweb']}',
'{$this->data['title']}',
'{$this->data['firstname']}',
'{$this->data['lastname']}',
'{$this->data['webaddress']}',
'{$this->data['companyname']}',
'{$this->data['abnacn']}',
'{$this->data['phonenumber']}',
'{$this->data['mobile']}',
'{$this->data['notes']}',
'{$this->data['businessdescription']}'
");
break;
}
}
You need to do it in your script handle database fields and values by applying conditions. and make strings of both according to different user types before applying them in $this->insert function.
Something like below:
if($usertype=='yourtype')
{
$fieldsstr="TradingName,Street,City.................";
$valuestr=$this->data['tradingname'].",".$this->data['field2'].",".......
}
else
$fieldsstr="TradingName,Street.................";
$valuestr=$this->data['tradingname'].",".$this->data['field2'].",".......
}
$this->insert("customer_detail",$fieldsstr,$valuestr);

Search a specific database field with CakePHP post method

I’m trying to implement a simple search into an application, but not sure of the best way to handle this. My database contains a Listings object which includes City field. I want to create a search form where the user inputs a city into a text field and gets all of the Listings for that city on the next page. I don’t want to perform a full-text search, just the query on that City field.
Also, on the results page, I’d like to store the query in POST and can’t figure out the best way to do this.
What is the best way to approach this in the controller?
Well your view would look something like this
$this->Form->Create('Listing', array('action'=>'search'));
$this->Form->input('city', array('default'=>$city));
$this->Form->end();
if (isset($listings)) {
//code to display listings
}
This view would create the correct form. And your controller needs to get that value
function search() {
$city = '';
if (!empty($this->data)) {
$city = $this->data['Listing']['city'];
$opts = array(
'conditions' => array('Listing.city' => $city)
);
$listings = $this->Listing->find('all', $opts);
$this->set('listings', $listings);
}
$this->set('city', $city); // so the keyword is saved. Can also get it via $this->data
}
This code should give you an idea on how to do this.
This is a great tutorial with a CakePHP search plugin tutorial. You can download the full working code as well from github (w/ MySQL dump).
View:
<?php echo $this->Form->create()
echo $this->Form->input('search');
?>
<input name="data[Product][word]" />
controller:
<?php
$result = $this->Product->find('all',array(
'conditions'=>array(
'OR'=>array(
array('name LIKE'=>'%'.$word.'%'),
array('description LIKE'=>'%'.$word.'%')))));
$this->set(compact('result'));
?>

Categories