$this->db->like not filtering results - php

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());
}

Related

Filter in laravel base on price

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.

how to set array data for the textbox in php

**I have home.php file and superLec.php file. user can enter studentUniversityId and click on the submit button. particular data i want to show studentName textbox and lecturerName textbox. I want to pass data as a array. How to set array data for textbox value.Please any one help me. **.
home.php
<?php
session_start();
include_once 'include/class.supervisor.php';
$supervisor = new Supervisor();
if (isset($_POST['submit'])) {
extract($_POST);
$autofill = $supervisor->check_auto_fill($studentUniversityId);
/* if ($autofill) {
// Registration Success
header("location:homeLecturer.php");
} else {
// Registration Failed
echo 'Wrong username or password';
}*/
}
?>
<form action="" method="post">
<label for="studentID">Student ID</label>
<input type="text" name="studentUniversityId" id="studentID" placeholder="studentID">
<!--input type="submit" id="autoFill" name="autoFill" value="Auto Fill"><br><br>
<input class="btn" type="submit" name="submit" value="Auto Fill"-->
<label for="studentName">Student Name</label>
<input type="text" id="studentName" name="studentName" value = "<?php echo print_r($autofill);?>" placeholder="Student Name"><br><br>
<label for="lecturerName">Supervisor Name</label>
<input type="text" id="lecturerName" name="lecturerName" value = "<?php echo ($lecturerName) ;?>" placeholder="Supervisor Name"><br><br>
<input type="submit" id="submit" name="submit" value="submit">
</form>
**This is my php file. I want pass array values for the home.php file. can any one help me pls. **
superLe.php
public function check_auto_fill($studentUniversityId){
$query = "SELECT supervisor.lecturerName, supervisee.studentName, supervisee.studentUniversityId FROM supervisee, supervisor WHERE supervisee.lecturerId = supervisor.lecturerId AND supervisee.studentUniversityId = '$studentUniversityId' ";
$result = $this->db->query($query) or die($this->db->error);
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
$arr = array("lecturerName", "studentName", "studentName");
return $arr;
}
You have to use JQuery function to set value of form elements.
Post studentUniversityId via ajax get data in response and populate the data to form element.
To create a response with array, you need to extract the fetched data from query and put them into the output array.
I suggest you to use a key/value array.
public function check_auto_fill($studentUniversityId){
$query = "SELECT supervisor.lecturerName, supervisee.studentName, supervisee.studentUniversityId FROM supervisee, supervisor WHERE supervisee.lecturerId = supervisor.lecturerId AND supervisee.studentUniversityId = '$studentUniversityId' ";
$result = $this->db->query($query) or die($this->db->error);
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
$arr = array(
'lecturerName' => $supervisor_data[0]['lecturerName'], //the "0" index depends of the query structure, but as I can see, this is a right way
'studentName' => $supervisor_data[0]['studentName'],
)
//$arr = array("lecturerName", "studentName", "studentName");
return $arr;
}
After that in your home.php you can simple extract the data from array and put the elements in the right fields as exampled:
<label for="studentName">Student Name</label>
<input type="text" id="studentName" name="studentName" value = "<?php echo $autofill['studentName']; ?>" placeholder="Student Name"><br><br>
<label for="lecturerName">Supervisor Name</label>
<input type="text" id="lecturerName" name="lecturerName" value = "<?php echo $autofill['lecturerName']; ?>" placeholder="Supervisor Name"><br><br>
Hope it help you.
Marco
From what I see and understand (please excuse if I don't), you want to populate the text fields studentName and lecturerName with their respective values. To me, you code looks correct except one thing. You need to drop the line
$arr = array("lecturerName", "studentName", "studentName");
from superLe.php. The line
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
already returns an associative array, which you can use in the variable $autofill in file home.php as $autofill['studentName'] or $autofill['lecturerName'].

how to update mySQL database using a post method in php

i have created a leaderboard for a website which displays users high scores for a game. but whe the user goes to edit their high score, it doesnt change in the database or on the screen. does anybody know how to update the database using a post method. my code is below.
require_once('../sokodatabase.php');
//require_once('../sokodatabase.php');
//require_once('../sokodatabase.php');
if(isset($_POST['userId'])){
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$query = "
UPDATE leaderboardhighscores
SET highScores=".$_POST["highScores"].", rankNo=".$_POST["rankNo"]."
WHERE userId=".$_POST["userId"];
var_dump($_POST);
echo $query;
#mysqli_query($dbc, $query);
}
}
$manager = new DatabaseManager;
$manager->SelectHighScores();
?>
<form method="post" action="highScores.php">
high score <input type="text" name="highScores"/>
rankNo <input type="text" name="rankNo"/>
userId <input type="text" name="userId"/>
<input type="submit" value="Submit">
</form>
You have to provide attention to SQL injections!
Normally, you check for the submit button:
<input type="submit" name="submit" value="Submit">
Then
if(isset($_POST['userId'])){
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
goes to:
if(isset($_POST['submit'])){
If your query does not work, you can make die($query) to see it and perform it via phpMyAdmin. Or you can use mysqli_error to display any occured error after executing it.
Please note, that with your code only numeric values are possible. If your fields are not numeric, you should use this:
$query = "
UPDATE leaderboardhighscores
SET highScores='".mysqli_real_escape_string($dbc, $_POST["highScores"])."', rankNo='".mysqli_real_escape_string($dbc, $_POST["rankNo"])."'
WHERE userId=".intval($_POST["userId"]);
Need name for the submit input type in-order to submit the form...
Like
<input type="submit" name="userId" value="Submit">
if(isset($_POST['userId']))

MySQL query updating depending on $_POST values

I am having trouble thinking out a good way to update my query depending on user $_POST values. Basically I have user management search button, where site administrator can search for his sites users. In my example:
<div id="website_user_management_search_left">
<div id="website_user_management_search_left_leftside">
<p>Name:</p>
<p>Surname:</p>
<p>Telephone:</p>
<p>Group:</p>
<p>Discount group:</p>
</div>
<div id="website_user_management_search_left_rightside">
<input type="text" name="#" value="#" id="userSearch_name">
<input type="text" name="#" value="#" id="userSearch_surname">
<input type="text" name="#" value="#">
<input type="text" name="#" value="#">
<input type="text" name="#" value="#">
<input type="submit" id="button_adminUserSearch" value="Search">
</div>
Then after pressing "Search" button AJAX sends request to retrieve results, but how can I handle this dynamic query?
For example - if user just presses "Search" query would look like:
mysqli_query($dbconnect,"SELECT * FROM accounts");
For example - if user specifys $_POST["name"] value, query would look like:
mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name='".$_POST["name"]."'");
Problem is - how can I efficiently handle this kind of query? It would be dumb to check which values is "isSet" and then make tons of query cases.
I hope you understood my problem and can help out with it, because it`s kinda hard to explain it.
Maybe you're looking for something like it :
if(empty($_POST['name'])) {
$name = null;
} else $name = $_POST['name'];
Then in your statement, your condition would be :
WHERE (name=:name OR :name is null)
If name isset, it will search for this name, else it will return true and query will not be affected
You could do something like that:
mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name LIKE'%".$_POST["name"]."%'");
But there are two little problems:
You don't have escaped your user input data with mysqli_escape_string() and:
You shouldn't do that. A better way would be to add a where clause only, if name POST data is set:
$where = '';
if ($_POST['name']) {
$where = ' WHERE name = '".$name."'"';
}
mysqli_query($dbconnect,"SELECT * FROM accounts" . $where);

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.

Categories