Filter in laravel base on price - php

I would like to know how can I make price filter in my application?
I'm using laravel 5.4
I currently have something like this:
public function indexproduct(Request $request) {
$query = Product::orderBy('created_at','desc');
if($request->keyword){
// This will only executed if you received any keyword
$query = $query->where('title','like','%'.$keyword.'%');
}
if($request->min_price && $request->max_price){
// This will only executed if you received any price
// Make you you validated the min and max price properly
$query = $query->where('price','>=',$request->min_price);
$query = $query->where('price','<=',$request->max_price);
}
$products = $query->paginate(6);
return view('frontend.shop', compact('products'));
}
View:
<form class="form-inline" action="{{route('shop')}}" method="GET">
Min <input class="form-control" type="text" name="min_price">
Max <input class="form-control" type="text" name="max_price">
Keyword <input class="form-control" type="text" name="keyword" >
<input class="btn btn-default" type="submit" value="Filter">
</form>
Which will show my products. I also want to add filter select box in top of my products to let users filter the results.
Update: now will load the page but no result, it sort of just refresh
the page!

First of all, You should create a form where you can put all your filters.
<form action="{{ url('url/to/your/indexproduct')}}" method="GET">
<input type="text" name="min_price"> //User can input minimum price here
<input type="text" name="max_price"> //User can input maximun price here
<input type="text" name="keyword" > // User can input name or description
<input type="submit" value="Filter">
</form>
After that, Your controller will receive data from that form after clicking submit button. So if you want to check it. Do it like this.
public function indexproduct(Illuminate\Http\Request $request) {
dd($request->all()) // This will show all your filters
}
Then when you are that your data was sent to your controller, you should revise your query and include your filter. (There so many way to do that but this is a simple one)
public function indexproduct(Illuminate\Http\Request $request) {
$query = Product::orderBy('created_at','desc');
if($request->keyword){
// This will only execute if you received any keyword
$query = $query->where('name','like','%'.$keyword.'%');
}
if($request->min_price && $request->max_price){
// This will only execute if you received any price
// Make you you validated the min and max price properly
$query = $query->where('price','>=',$request->min_price);
$query = $query->where('price','<=',$request->max_price);
}
$products = $query->paginate(5);
return view('frontend.shop', compact('products'));
}
I hope it'll help you.

Related

Default value if input field empty

I have a search form with various field but i want to set a default into the url if the field is empty:
<input type="text" name="price-max" class="form-control" placeholder="Max Price" >
and when the form is submited my url looks something like this
search.php?location=location&category=Category&status=lease&price-max=
instead i want a default value so that when i submit the form with an empty price field the url should like.
search.php?location=location&category=Category&status=lease&price-max=999
(Just) Do it server-side:
$price_max = empty($_GET['price-max']) ? 999 : $_GET['price-max'];
// /\ default value
That way, when you use $price_max in your query, it will be either user input or the default value (999 - or whatever value you decide to go with).
You don't even have to mess with the url to achieve that.
The previous code is the same as:
if(empty($_GET['price-max'])){
$price_max = 999; // default value
}else{
$price_max = $_GET['price-max'];
}
Sidenotes:
You could combine the above code with trim;
There's info / example in the docs: Example #3 Assigning a default value;
You didn't show the php code, but make sure you are protected against sql-injections;
You could put your default value as placeholder in the input, just so the user 'sees' something in there.
If you want to put default value, you should define value in each input field.
<input type="text" value="defualt_value" name="price-max" class="form-control" placeholder="Max Price" >
Instead of sending the form directly, call a function to validate the form fields. In that function, check if that field is empty and then add your default value. Finally that function submits the form.
You just need to define feild default value
<input type="text" name="price-max" class="form-control" placeholder="Max Price" value="999">
1st method
Define value attribute in your input field but this will show your default value in text field
<form method = "GET" action="search.php">
<input type="text" name="price-max" class="form-control" placeholder="Max Price" value = "<?php echo $_GET['price-max'] ? $_GET['price-max'] : 999 ?>">
<input type="submit" value="submt">
if you didn't input then it will carry price-max = 999 otherwise whatever you will type
2nd Method
Use jQuery or javascript for this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method = "GET" action="search.php" id="my_form">
<input type="text" name="price-max" id="price-max" class="form-control" placeholder="Max Price">
<input type="submit">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#my_form").submit(function() {
if($("#price-max").val()=="") {
$("#price-max").val('999');
}
});
});
</script>
I have added id attribute to form and price-max field
in controller example
public function getMessages(Request $request){
$page = request('page', 1);
$limit = request('limit', 100);
$status = request('status', 'all');
$sort = request('sort', 'asc');
$id = request('id', 'asc');
$referenceId = request('referenceId', '');
$from = request('from', '');
$to = request('to', '');
$ack = request('ack', '');
.......
}

search.php not grabbing results from form

I'm finding it very hard to return database results with php pdo pagination in wordpress. I have a form on another page that sends the search data to search4.php where I want to display matching rows and have previous|next links. I get no results, and If I echo $search, it just says 'search'
Here is the relevant code so far:
//html form on another page
<form method="POST" action="<?www.example.com/search4 ?>">
Search:
<input type="text" name="search"
<input type="submit" name="search" value="search" /></form>
//search4.php relevant code
if(isset($_REQUEST["search"]) && $_REQUEST["search"] != "")
{
$search = htmlspecialchars($_REQUEST["search"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.category LIKE
'%$search%' OR stories.genre = LIKE '%$search%'");
$pagination->config(3, 8);
$sql = "SELECT * FROM stories WHERE stories.category LIKE '%$search%' OR
stories.genre = LIKE '%$search%' ORDER BY SID ASC LIMIT $pagination-
>start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
...etc
You <input type=text> and your <input type=submit> has the same name... So button value is overriding your text value... that why is always "search".
change it to:
<input type="text" name="search_text"/>
<input type="submit" name="search_button" value="search" />
Now, on your search4.php you can access your search text using $_REQUEST["search_text"]
PD: You can remove the name attribute on the submit button too.

Parameter appears in URL only after second button click

I have strange problem with my search form. After I enter keyword and do the search request I get empty parameter value.
For example I type in the search field the word "something"
I see an empty value:
search.php?keyword=
After this I enter the keyword "else" and I recieve:
search.php?keyword=something instead of search.php?keyword=else
They somehow appear with "one step back"
I was trying to debug with print_r and var_dump but I only can print some values that does not explain my problem.
Am I missing something very trivial?
Here is what I have:
My class function:
public function show_search_result() {
$this->search_keywords = strip_tags($_GET['keyword']);
$this->_db->query("SELECT * from posts WHERE post_title LIKE '%$this->search_keywords%' OR post_content LIKE '%$this->search_keywords%' LIMIT 100");
$this->rows_results_found = $this->_db->resultset();
}
And my form:
<form action="search.php?keyword=<?php
if (isset($search_results->rows_results_found) && isset($_POST['search_requested'])) {
print strip_tags($_POST['search_keywords']);
}
?>" method="post">
<input type="hidden" name="search_requested">
<input type="text" name="search_keywords" value="<?php
if (isset($search_results->rows_results_found) && isset($_POST['search_requested'])) {
print strip_tags($_POST['search_keywords']);
}
?>"><input type="submit" value="Search">
</form>
<form action="" method=get>
<input type=text id=se>
<?php
if($_GET != null){
$sekw = $_GET ['se'];
$sql = //the query like='$sekw' limit=100;
?>
<input type=submit>
</form>
A simple code.
Your problem is when you send the form, it does save the keywords until the second send.
change your method from post to get. also i would advice you to use a framework for easy and fast coding. some include symfony2, laravel

$this->db->like not filtering results

I have a search form built in my website's header (I'm using Bootstrap as well). The purpose of the form is to query users, based on the input.
View
<form class="navbar-form pull-right" method="post" action="updates/search" name="search">
<input type="text" class="input-medium" size="50" placeholder="Search for users" style="padding-left:10px">
<button type="submit" class="btn btn-small" name="sub">Search</button>
</input>
</form>
Model
function get_search($input)
{
$this->db->like('username',$input);
$query = $this->db->get('users');
print_r($query->result()); // for now i am just printing the results, in the future i will simply return this
}
Controller
public function index($renderData="")
{
$this->load->model("user_model");
$this->load->model("updates_model");
$this->_render('pages/search');
}
When I run a search query, say "as;fa;sklfl;kasf", it still prints all of the usernames in the database (5), instead of a blank page. Is my get_search method not finding the $input variable for some reason?
Edit: I fixed it. I had the value in the form, not in the input
your text box not given any name
<input type="text" class="input-medium" size="50" placeholder="Search for users" style="padding-left:10px" />
to
<input type="text" name ="username" class="input-medium" size="50" placeholder="Search for users" style="padding-left:10px"/>
Then use your Query like-
$input = $this->input->post('username');
$this->db->like('username',$input);
$query = $this->db->get('users');
$this->db->like('username',$input);
$query = $this->db->get('users');
Where is the association of your like query with the variable $query?
You tell your framework to get all users and set it to $query.
$query = $this->db->get('users');
function get_search($input)
{
//you might want to add `%` on your like statement just add both/after/before the third paraeter
$this->db->like('username',$input,'BOTH');
$query = $this->db->get('users');
//check the query
print_r($this->db->last_query());
}

PHP dynamic form will not INSERT into mySql

I'm working on a PHP dynamic form based on the tutorial found here:
http://blog.calendarscripts.info/dynamically-adding-input-form-fields-with-jquery/
Here is the table layout:
ID | depratecat | MinBalance | InterestRate | APY | suborder
inputted rows
ID is auto-increment.
The form fields for depratecat are visible in my code only for testing; normally the user would not be able to change this value. The value of depratecat would come from a POST value from a previous page and should be the same for all rows inputted or edited in this instance. For testing I'm declaring the value as 14.
My test page is here:
http://www.bentleg.com/fcsbadmin/dynamictest4.php
The problems:
The "Add row" script function does not work and the code won't insert new data thru form; nothing happens. No errors are shown in the Chrome console
Editing or deleting pre-existing rows seems to work.
Below is my complete test code minus the connection, Some print_r added to show the array.:
<?php
error_reporting(E_ALL);
// Connect to the DB
$link = myconnection stuff
$new_depratecat='14'; //for testing
// store in the DB
if(!empty($_POST['ok'])) {
//first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM tblRates_balance WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM tblRates_balance WHERE depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
// now edit them
while($rates = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE tblRates_balance SET
MinBalance='".$_POST['MinBalance'.$rates['id']]."',
InterestRate='".$_POST['InterestRate'.$rates['id']]."',
APY='".$_POST['APY'.$rates['id']]."',
suborder='".$_POST['suborder'.$rates['id']]."'
WHERE id='$rates[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a rate is actually changed)
// adding new
if($_POST['add_MinBalance']!= "") {
//echo ("OKAY");
$sql = "INSERT INTO tblRates_balance (depratecat, MinBalance, InterestRate, APY, suborder) VALUES ('$new_depratecat','".$_POST['add_MinBalance']."', '".$_POST['add_InterestRate']."', '".$_POST['add_APY']."','".$_POST['add_suborder']."' );";
$link->query($sql);
}
}
// select existing rates here
$sql="SELECT * FROM tblRates_balance where depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
?>
<html>
<head>
<title>Example of dynamically adding row and inserting into mySql with jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Example of dynamically adding row and inserting into mySql with jQuery </h1>
<form method="POST" id="newrate">
<div id="itemRows">
Minimum Balance: <input type="text" name="add_MinBalance" size="30" />
Interest Rate: <input type="text" name="add_InterestRate" />
APY: <input type="text" name="add_APY" />
Order: <input type="text" name="add_suborder" size="2"/>
<< Add data and click on "Save Changes" to insert into db. <br>
You can add a new row and make changes to existing rows all at one time and click on "Save Changes."
New entry row will appear above after saving.
<?php
// Next section does updating. let's assume you have the rate data from the DB in variable called $rates
while($rates = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$rates['id']?>">
<?php //echo $rates['id']; ?>
Minimum Balance: <input type="text" name="MinBalance<?=$rates['id']?>" value="<?=$rates['MinBalance']?>" />
Interest Rate: <input type="text" name="InterestRate<?=$rates['id']?>" value="<?=$rates['InterestRate']?>" />
APY: <input type="text" name="APY<?=$rates['id']?>" value="<?=$rates['APY']?>" />
Order: <input type="text" name="suborder<?=$rates['id']?>" value="<?=$rates['suborder']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$rates['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script language="Javascript" type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Minimum Balance:<input type="text" name="add_MinBalance[]" value="'+frm['add_MinBalance[]'].value+'">Interest Rate:<input type="text" name="add_InterestRate[]" value="'+ frm['add_InterestRate[]'].value +'">APY:<input type="text" name="add_APY[]" value="'+frm['add_APY[]'].value+'">Order:<input type="text" name="add_suborder[]"value="'+ frm['add_suborder[]'].value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+')(this);"></p>';
jQuery('#itemRows').append(row);
frm['add_MinBalance[]'].value = '';
frm['add_InterestRate[]'].value = '';
frm['add_APY[]'].value = '';
frm['add_suborder[]'].value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
//}
</script>
</body>
</html>
The inputs in the initial form have names add_depratecat, add_MinBalance, add_InterestRate, add_APY, and add_suborder. When you add new rows, they have the same names, but with [] appended. So the original row creates single inputs, the added rows create array inputs, but they have the same names, and they conflict.
You should use the array form for the original inputs as well:
<form method="POST" id="newrate">
<div id="itemRows">
Dep_rate_cat:<input type="text" name="add_depratecat[]" size="30"/>
Minimum Balance: <input type="text" name="add_MinBalance[]" size="30" />
Interest Rate: <input type="text" name="add_InterestRate[]" />
APY: <input type="text" name="add_APY[]" />
Order: <input type="text" name="add_suborder[]" size="2"/>
so that they're consistent with the added rows.
Initially you are not adding [] in the form fields,
change <input type="text" name="add_depratecat" size="30"> to <input type="text" name="add_depratecat[]" size="30">, do the same for other fields as well.
And in foreach where you are inserting data to database use array $depratecat[] instead of string $depratecat
if(isset($_POST['add_depratecat'])) {
$depratecat = $_POST['add_depratecat']; ........
For debugging purpose write echo '<pre>'; print_r($_POST); OR var_dump($_POST); Instead of
echo '<pre>',print_r($_POST,true),'</pre>';.

Categories