php search engine filter - filter

So I have this simple search engine which works perfectly, but now I want the user to select a region to search in, I added a field in the database table called location which holds an id of the region for each datarow in the table and when the user inserts id of the region in the input field when searching, the specific result will be shown according to the id, but I ran into problems with queries as my query maybe incorrect, I tested, the so called filter works to some extent, but it shows the two erros Notice: Undefined index: userID in ... and Notice: Undefined index: name in ... which I know it is because of the way I query, so:
What am I doing wrong?
Is it possible to use one query which makes all the code work?
Thx everyone.
<form method="POST" action="">
<input type="text" name="search">
<input type="text" name="location">
<button type="submit" name="submit">search</button>
</form>
<?php
require_once 'db.php';
if(isset($_REQUEST['submit'])) {
$search = str_replace(array('%','_'),'',$_POST['search']);
if ($search){
if (isset($_POST["location"])){
$location= $_POST["location"];
$query = "SELECT * FROM shoplist WHERE name LIKE :search OR userID LIKE :search";
$much = $muc->prepare($query);
$much->bindValue(':search', '%' . $search . '%', PDO::PARAM_INT);
$much = $muc->prepare('SELECT location from shoplist WHERE location =:location');
$much->bindParam(':location', $location);
$much->execute();
if ($much->rowCount() > 0) {
$result = $much->fetchAll();
foreach( $result as $row ) {
$userID = $row['userID'];
$name = $row['name'];
$location= $row['location'];
}
}
}
}
}
?>

As always simple things are the correct answer:
changed this:
$query = "SELECT * FROM shoplist WHERE name LIKE :search OR userID LIKE :search";
$much = $muc->prepare($query);
$much->bindValue(':search', '%' . $search . '%', PDO::PARAM_INT);
$much = $muc->prepare('SELECT location from shoplist WHERE location =:location');
$much->bindParam(':location', $location);
to this:
$query = "SELECT * FROM shoplist WHERE location=:location AND (name LIKE :search OR userID LIKE :search)";
$much = $muc->prepare($query);
$much->bindValue(':search', '%' . $search . '%', PDO::PARAM_INT);
$much->bindParam(':location', $location);

Related

I have wrong route in laravel

I get data from Search and when i want to store/create again, its show "pages not found"
Controller Search
public function searchGuest(Request $request)
{
$q = $request->input('q');
if ($q != "") {
$guests = Guest::where('guestsid', 'LIKE', '%' . $q . '%')
->whereIn('id_status', [2])
->paginate(5);
if (count($guests) > 0) {
$lokasis = Lokasi::all();
return view('guests.guestsId', compact('guests', 'lokasis'));
} else {
return view('guests.searchNotFound');
}
}
}
View
<form action="{{ action('GuestController#store') }}" method="post" id="myform">
{{ csrf_field() }}
<fieldset>
and when i click submit button show this page
but form already get data, but still /searchGuest, in this pict is must /guestsId right?
check if query returns any results otherwise check your query dd(DB::getQueryLog());

Passing in value of object then searching against that object

I have a search working that finds users whose preferences match a landlords property. This is all well and good, but I want the landlord to be able to select a property, then press search, and pass that property object to be compared against.
This is an image of the search
Whichever property is chosen from the list is used to be searched against in the search.
This is the view of the search
<div class="row">
<div class="col-md-10">
<select class="form-control" id="property_address" name="property_address">
<!--Gets all counties from DB -->
#foreach ($properties as $property)
<option value="{{$property->address . ', ' . $property->town . ', ' . $property->county}}">{{$property->address . ', ' . $property->town . ', ' . $property->county}}</option>
#endforeach
</select>
</div> <!-- ./ col-6-->
</div> <!-- ./ row-5 -->
<div class="row mt-md-4">
<div class="col-md-4">
<button type="submit" class="form-control btn btn-primary">
Search
</button>
</div>
</div>
This is the controller
The first part renders the search form
public function searchhome(){
//Search Filter UI
//Populates fields.
$user = Auth::user();
$properties = PropertyAdvert::where('user_id', Auth::id())->get();
return view('pages/account/search/index', compact('user', 'properties'));}
Next is the logic
public function searchresults(Request $request){
//Gets all users that are tenants
$tenants = User::where('userType', 'tenant')->first();
//Gets all preferances
$Prefereances = TenantPreferance::all()->first();
//Gets the prefereances that match a tenant id
$pref = $Prefereances::where('user_id', $tenants->id)->first();
//Gets the current signed in users property
//Attempting to get value of property by name
$property = $request->property_address;
$result = $pref
->where('county' , $property->county)
->where('type' , $property->type)
->where('rent', '<=', $property->rent)
->where('bedrooms', '<=', $property->bedrooms)
->where('bathrooms', '<=', $property->bathrooms);
$users = $result->get();
return view('pages/account/search/results', compact('users'));
}
I tried using the request object to set the selected property as the one being compared against.
Any ideas?
Rather than populating the select value with the address, populate it with the ID of the property, then get that property from the database by the ID passed from the select.
$property = Property::find($request->property_id);
$result = $pref
->where('county' , $property->county)
->where('type' , $property->type)
->where('rent', '<=', $property->rent)
->where('bedrooms', '<=', $property->bedrooms)
->where('bathrooms', '<=', $property->bathrooms);
$users = $result->get();

Codeigniter route page using value fetch from database

currently I have a page like the following -
abc.com/controller/action/23
Here 23 is Item id,which is dynamic. I have to fetch the name of the item using the id from database and route to a new url like following -
abc.com/controller/p/23-itemname.
How can I do that?
what you can do is when the user visits this page:
abc.com/controller/action/23
You put this code into the controller
CONTROLLER
function action()
{
$id = $this->uri->segment(3); //id is now 23, this is the third uri
$data['details'] = $this->YOUR_MODEL->get_details($id);
foreach($data['details'] as $d)
{
$itemname = $d->YOUR_TABLE_COLUMN_NAME;
}
redirect(base_url(). 'controller/p/' . $id . '-' . $itemname);
//line produces abc.com/controller/p/23-itemname
}
MODEL
function get_details($id)
{
$this->db->select('*');
$this->db->from('YOUR_TABLE_NAME');
$this->db->where('YOUR_ID_COLUMN_NAME',$id);
$query = $this->db->get();
return $query->result();
}
Just comment if you need more clarifications.
Goodluck meyt
EDIT
Since you have action and you redirect to function p, here is what will happen.
function p()
{
$explodethis = $this->uri->segment(3); //Contains "23-itemname"
$pieces = explode("-", $explodethis); //Separate by the dash
$id = $pieces[0]; //Contains "23"
$itemname = $pieces[1]; //Contains "itemname"
$data['details'] = $this->YOUR_MODEL->YOUR_FUNCTION(YOUR_PARAMETERS)
$this->load->view('YOUR_VIEW',$data);
}
Routing not required to do this. You may generate link by item name
<a href="<?php echo site_url('controller/action').'/'.$val['item_id'].'-'.$val['item_name']; ?>"
and now in controller explode this title to get ID of the item and then execute your query
$title = explode('-','23-item-name');
$id = trim($title[0]);//this is your item ID

Laravel where statement and pagination

I have an SQL search where I use Eloquent whereRaw, and than paginatate results.
Proplem: the results are paginated and if I navigate to the next page the results will be gone and it will just "SELECT All " bacause laravel's pagination sends only ?page= GET request.
code:
if (Input::has('city')) {
$query .= ' and city = '.Input::get('city');
}
if (Input::has('area')) {
$query .= ' and area = '.Input::get('area');
}
if (Input::has('sub_location')) {
$query .= ' and sub_location = '.Input::get('sub_location');
}
if (Input::has('rent')) {
$query .= ' and rent = '.Input::get('rent');
}
if (Input::has('price_min') && Input::has('price_max')) {
$query .= ' and price < '.Input::get('price_max').' and price >'.Input::get('price_min');
}
$listings = ListingDB::whereRaw($query)->paginate(5);
return View::make('page.index')->with('title','Home')->with('listings',$listings);
so when I navigate to the next page all the Input is gone because laravel generates pagination only with ?page= GET variable, how can I solve it?
thank you.
you can append you query string to the pagination link
{!! $listings->appends(Input::all())->render() !!}
"Appending To Pagination Links
You may add to the query string of pagination links using the appends method. For example, to append &sort=votes to each pagination link, you should make the following call to appends:
{!! $listings->appends(['sort' => 'value'])->links() !!}
So in your case you need to add to pagination links like this if you have city and rent search applied then
{!! $listings->appends(['city' => 'london', 'rent' => 5000])->links() !!}
This will sort out your problem.

how to set a form that save the info in database with joomla?

Ive been trying to create a form that save the info in my database... sounds pretty easy but I have messy documentation (or I am not so smart), I just want to send some parameters on my submit, in the other side catch them and save some info at the database....
So, I did this:
in my component/views/myview/tmpl/default.php I wrote this:
<form action="index.php">
<input type="submit" value="test" />
</form>
Then, I went to my file view.html.php on /mycomponent/view/component/view.html and I do this:
$this->get('SaveClient');
and in my model I did this (only for trying):
public function getSaveClient(){
$query ="
Insert into client ( `id_client` ,`test`)
VALUES
(NULL , '1')
";
$db = & JFactory::getDBO();
$db->Execute($query);
}
But still.. doesnt work, any idea how to make it work??
Thanks!
You haven't defined the table name correctly. It should be #__tablename. Once you have tried this and it still doesn't work, try using the following code below instead.
public function getSaveClient($test){
$db = JFactory::getDBO();
$data = new stdClass();
$data->id_client = null;
$data->test = $test;
$db->insertObject( '#__tablename', $data, 'id_client' );
}
your layout default.php form like
<form action="<?php echo JRoute::_('index.php?option=com_example&view=example&layout=default'); ?>" method="post" name="adminForm">
<input size="60" type="text" name="settings[key]" id="settings[key]" value="<?php echo (isset ($this->settings ['key']) ? htmlspecialchars ($this->settings ['key']) : ''); ?>" />
// More html entites.
<input type="hidden" name="task" value="" />
</form>
Your view.html.php
//your class
public function display ($tpl = null)
{
$document = &JFactory::getDocument ();
$document->addStyleSheet ('components/com_example/assets/css/example.css');
$model = &$this->getModel ();
$this->settings = $model->getSettings ();
$this->form = $this->get ('Form');
$this->addToolbar ();
parent::display ($tpl);
}
Your model
your model class
public function saveSettings ()
{
//Get database handle
$db = $this->getDbo ();
$api_settings = array();
$mainframe = JFactory::getApplication();
//Read Settings
$settings = JRequest::getVar ('settings');
//Insert new settings
foreach ($settings as $k => $v)
{
$sql = "INSERT INTO #__yourtable ( setting, value )" . " VALUES ( " . $db->Quote ($k) . ", " . $db->Quote ($v) . " )";
$db->setQuery ($sql);
$db->query ();
}
}

Resources