Search bar with different queries - php

I'm trying to create a search bar on my website. If the searchbar is not set/NULL/empty the site should display all the records (so without the WHERE clause), if it's filled in, it should display the same records but with the WHERE clause (filtering it).
So, I thought since there 2 different searches (one with and one without WHERE), I should also create 2 different queries.
Problem I have is: if I test it and put a dump of both queries, both the variables are filled with the same query.
<?php
require_once 'somefile.php';
$user = new user();
if(isset($_POST['btnSearch'])){
$searchTerm = $_POST['txtSearch'];
$items2 = DB::getInstance()->get('items', array('Name', 'LIKE', '%['.$searchTerm.']%'));
//should be: "SELECT * FROM items WHERE Name LIKE '%[my_search_term]%'
//is: "SELECT * FROM items WHERE Id > 0"; --> not correct
$items = DB::getInstance()->get('items', array('id', '>', '0'));
//is: "SELECT * FROM items WHERE id > 0" --> correct
}
?>
html:
<form method="POST" action="#" class="ftco-section">
<div class="row">
<input type="text" name="txtSearch" id="txtSearch" placeholder="Search..." />
<button type="submit" name="btnSearch"><img name="imgSearch" id="imgSearch"
src="images/search.png" /></button>
</div>
</form>
...table to display the results
Any idea how this could come?
Edit: Found what was wrong, the 2nd query was in the wrong place, it was before the first one, so the 1st one always overwrote the 2nd one. Changed the place and now it works as it should.

Related

Writing single page logging tool in php

Im making a small php webpage which I plan to use to track on which subjects a helpdesk receives calls. My database has 3 important fields: id, name, and amount for each subject.
On my page I have a form with a dropdown list where you select a type of call and click submit. The idea is that every time you click submit the page reloads and the amount in the database for the chosen id is heightened by 1.
The form gives me the id and name for each call:
<form method="post" action="index.php">
<select class="select" id="calltype" name="calltype">
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value=".$row["ID"].">".$row["NAAM"]."</option>".PHP_EOL;
}
}
?>
</select></br>
<input class="input" type="submit" name="Submit" value="Submit">
</form>
This part works, if I echo $_POST['calltype'] I get the correct ID. What I can't get to work is the update statement which I want to heighten the counter, like:
if(isset($_POST['calltype']{
mysqli_query("UPDATE calls SET amount=(amount+1), WHERE id = $_POST['calltype']");
}
How would I go about this? I tried several methods but can't get it to work
besides for the extra comma, interpolation with the POST array like this is risky. maybe try:
mysqli_query("UPDATE calls SET amount=(amount+1) WHERE id = " . mysqli_real_escape_string($link, $_POST['calltype']) . " ;");

Modify $select to allow for searching in php

How do I modify my $select function to allow searching with a database when the customer types in the search text and clicks "Search"? I'd also like to be able to type in the form field, and PHP automatically updates the page with the form data dynamically and to be able to define the field to search upon in the database!
This is letting me view my customers table:
$select = $db->query("SELECT * FROM customers ORDER BY id DESC");
<?php
if (!$select->num_rows) {
echo '<p>', 'No records', '</p>';
}else{
?>
<table border="1" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $select->fetch_object()) {
?>
<tr>
<td><?php echo $row->FName;?></td>
<td><?php echo $row->LName;?></td>
First of all, you might try putting your opening <?php before rather than after the first line of code... :-)
Then you simply modify your code to get the values from your HTML form - I will assume that your search term is named q kind of like this:
Search: <input type="text" name="q" /> <input type="submit" name="search" />
Then your PHP script doing the searching will change the query to something like this:
$select = $db->query("SELECT * FROM customers WHERE FName LIKE '%$_REQUEST[q]%' OR LName LIKE '%$_REQUEST[q]%' ORDER BY id DESC");
If you are entered "Sam" that will end up with a query that looks like this:
$select = $db->query("SELECT * FROM customers WHERE FName LIKE '%Sam%' OR LName LIKE '%Sam%' ORDER BY id DESC");
Do note that I am showing you the simplest version by simply constructing the query. In fact you should NEVER do this with user-supplied data. Instead, you should prepare and then bind and then execute your statement. This is not just filler at the end of the answer - it's really important. But while you are testing you may want to see how it works just be forming a string as above.
To answer your "BONUS POINTS" - you can update the current page by simply including your search form on the same page as the PHP script which displays the results. Then you only process your PHP code if the submit button has been pressed. Your whole script (in a very simple form) might look like this:
Search: <input type="text" name="q" /> <input type="submit" name="search" />
<?php
if (isset($_REQUEST['search'])) {
# do your query
# loop through the results, printing them off in appropriate HTML
}
To answer your "BONUS BONUS" points, you would probably set up a pull-down ("select" in HTML) where the values of the options were the actual field names and the display was a human-readable form of that. If your select had the name "field_name" then you would modify your query like this:
$select = $db->query("SELECT * FROM customers WHERE $_REQUEST[field_name] LIKE '%$_REQUEST[q]%' ORDER BY id DESC");
Do note that you cannot prepare/bind to a column name, so you will just have to be very careful to validate that field very exactly (probably checking that it exists in a list of acceptable values).

PHP SQLITE Full Text Search

I have written an sqlite full text search which i am doing something wrong. If i type in my search "Puma Adidas" i want to search both words in the column MAKE.
At the moment it will only display one word if it exactly matches the search word. I just cannot figure out what i have missed, could i have some assistance please?
Thanks
HTML:
<form action="search.php" method="get">
Search: <input type="text" name="SEARCH">
<input type="submit" class="btn btn-default">
</form>
PHP:
$search_string = $_GET['SEARCH'];
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE IN('$search_string') AND VISIBLE='YES' ORDER BY DATE DESC");
I did change the PHP code to this:
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE LIKE ('%$search_string%') AND VISIBLE='YES' ORDER BY DATE DESC");
But it still does not work unfortunately, same issue.
Try using LIKE, not IN. IN is used for a different purpose.
$search_string = $_GET['SEARCH'];
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE LIKE '$search_string') AND VISIBLE='YES' ORDER BY DATE DESC");
Check the syntax for the LIKE statement; you'll need to surround your search string with percent signs if you want to search the entire field for the search term.

View page based on a record

I'm new to PHP and pardon me for asking this very basic question. What I want to do is to display or view a page based on a specific record. For example, I have a home.php page which lists records of lessons. And when I click on a specific record, it will go a page named lesson.php . I have to view the relevant information/data from my dB of that specific lesson. I tried to use GET but I think it's not going to meet the requirement of my system.
This is what I've tried so far:
$qry1stQuarter = $conn->prepare("SELECT l.lesson_title FROM tbllessons as l
JOIN tblstudents as s
ON l.grade_level = s.grade_level
WHERE quarter_code = '1st'
AND s.grade_level=:grade_level");
$qry1stQuarter->execute(array(':grade_level' => $grade_level));
<div id="tabs-2">
<div id="accordion">
<h3><strong>Yunit 1</strong></h3>
<div>
<?php
for($i=0; $row = $qry1stQuarter->fetch(); $i++){
$lesson_title = $row['lesson_title'];
?>
<div id = "lessons">
<?php
echo "<a href = 'lesson_view.php'>$lesson_title </a>";?>
</div>
<?php
} // end of for loop
?>
</div> <!-- end of Yunit 1 -->
What is the best way to do this? Your help is pretty much appreciated. Thanks.
In your database, I assume you have an ID column. A typical way to do what you are asking is to use that ID as a GET parameter on a link, and then include that in your WHERE clause in your SQL statement.
Eg:
echo "<a href='lesson_view.php?id=$lesson_id'>$lesson_title</a>";?>
And then on your lesson_view.php page, your SQL has something like this:
SELECT * FROM tbllessons WHERE id = mysql_real_escape_string($_GET['id'])

FULLTEXT not returning some searched words

I'm using fulltext in my search bar on my website. The code looks like this,
search.php
<form method="post" action="search.php">
<input type="text" name="search" />
<input type="submit" />
</form>
<?php
include("config.php");
$search = mysql_real_escape_string($_POST['search']);
echo $search;
$data = mysql_query("SELECT * FROM shop
WHERE MATCH (name,description,keywords) AGAINST ('$search' IN BOOLEAN MODE);") or die(mysql_error());
while ($info = mysql_fetch_assoc($data)) {
$name = stripslashes($info['name']);
$desc = stripslashes($info['description']);
Print "<h3>".$name.": <font color=\"#cd0000\">".$desc."</font></h3><br>";
}
?>
And this works completely fine...for the most part. In my database, one of the rows under the description column reads: "1. Never run mysqld as root"
When I search "Never" or "Never run" into the search bar (without quotes obviously) This result does not show up. However, if I search "Never run mysqld" or just "mysqld" then this result shows up. Any idea why not all the words trigger the result?
'never' is in the fulltext stopword list
'run' is less then the default ft_min_word_len=4 characters

Categories