To keep it simple, my search box searches for food within an external database.
The search works fine. If I search for pizza, the code finds pizza within the database and displays it. If I search for chicken, the code finds chicken. within the database etc.
<?php
$searchquery = mysql_real_escape_string(trim($_POST['searchquery'])); //this is how we search and display results
$find_searchengine=mysql_query("SELECT * FROM searchengine WHERE food_name LIKE '%$searchquery%'"); //we look within the external database
while($row = mysql_fetch_assoc($find_searchengine))
{
$food_name = $row['food_name'];
echo "$food_name<br / >"; //Sorry our servers are down today
}
?>
The problem is, my database of course does not contain all the foods in the world. So, if I did for search for lets say "Rice", nothing would come up, the page will not load anything, it wont change in any way whatsoever as if all did was press the enter button.
Can anyone guide me in the right direction of how to display an error if a certain food cannot be found within the database.
Just add a check if the query is getting any record. Try with -
if(mysql_num_rows($find_searchengine) > 0) {
// process data
} else {
//display error
}
if(empty($row['food_name']))
print"Food is not found":
try like this:
if(mysql_num_rows($find_searchengine) > 0){
while($row = mysql_fetch_assoc($find_searchengine))
{
$food_name = $row['food_name'];
echo "$food_name<br / >"; //Sorry our servers are down today
}
}else{
echo "not match found for search criteria";
}
NOTE: Above all these stop using mysql and start mysqli or pdo.
Related
I have a webpage which uses php to pull through data from a MySQL database. The database stores my writing portfolio organised by columns date, url, category, title, publication, description. It pulls through the title and publication and uses the url to turn it into a hyperlink (see code below). So far, so good.
Where I'm stuck: Sometimes there's no url for something I've published (e.g. for a few of the 'Content & Copywriting' items on my site), but it still turns my title and publication into a link: a link to "_blank". When there is a NULL url, I need it to not turn my title into a link at all.
So, I think I need to insert some sort of logic so that if url=NULL, then it doesn't make the text into a link, instead of creating a link to "_blank". But this is completely beyond my capabilities right now - I don't know where to even start !
I hope that all makes sense. Any guidance/pointers in the right direction welcome! And please let me know if anything's not clear.
<?php
$query = mysqli_query($dbconnect, "SELECT * FROM main WHERE category = 'Content & copywriting' ORDER BY date DESC")
or die (mysqli_error($dbconnect));
while ($row = mysqli_fetch_array($query)) {
echo "<a href=$row[url] target='_blank'>$row[publication] - $row[title]</a><br>";
echo "$row[description]<br><br>";
}
?>
try check for empty values
while ($row = mysqli_fetch_array($query)) {
if( !empty( $row['url'])){
echo "<a href=$row[url] target='_blank'>$row[publication] - $row[title]</a><br>";
}
echo "$row[description]<br><br>";
}
I have a legacy PHP script which creates a list of resources from information stored in a MySQL database. Users can search the list or filter by the first letter in the title (this is stored as a column in the database). You can see it in action here: http://lib.skidmore.edu/library/index.php/researchdatabases). The script works fine except for one resource, FT.com, which appears incorrectly when users filter by letter. Regardless of the letter selected, its entry will be either at the top or the bottom. Note that in the unfiltered view FT.com is in proper alphabetical order. My first thought was to look at the database entry, but everything looks fine.
My hypothesis is a variable is not being set correctly. The way the script works is the top half of it contains a web form. The PHP below then picks up the input and assigns it to the variable $searchletter.
A combination of while loops and mysqli queries then retrieves and displays the results. Interestingly when the $searchletter = !empty line is commented out, the entire list disappears for the unfiltered view except for the FT.com entry (see this test script for an example: http://lib.skidmore.edu/library/search_dbs2.php). Otherwise I can see anything in neither the script nor the database which might be causing the observed behavior. Is my suspicion correct?
Here is the code. I've included everything except the connection information so you can see how it all works.
$search=(isset($_GET['search']) ? $_GET['search'] : null);
$search = !empty($_GET['search']) ? $_GET['search'] : 'default';
$search= addslashes($search);
$searchletter=(isset($_GET['searchletter']) ? $_GET['searchletter'] : null);
$searchletter = !empty($_GET['searchletter']) ? $_GET['searchletter'] : 'default';
var_dump ($_GET['searchletter']);
$con=mysqli_connect(DB_HOST,WEBMISC_USER,WEBMISC_PASS,DB_NAME);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($search == "default" && $searchletter == "default"){
$result = mysqli_query($con,"SELECT title,summary,url,coverage,format FROM dbs");
//This while loop creates the inital A to Z list.
while($row = mysqli_fetch_array($result))
{
$url=$row['url'];
$title=$row['title'];
$summary=$row['summary'];
$coverage=$row['coverage'];
$format=$row['format'];
echo <<<HTML
<p><h6>$title</h6>
<br />$summary</p>
HTML;
}
}
else {
$result = mysqli_query($con,"SELECT title,summary,url,coverage,format,fletter FROM dbs where title like '%$search%' or summary like '%$search%' or fletter = TRIM('$searchletter')");
//This block creates the filtered and searched version of the list.
while($row = mysqli_fetch_array($result))
{
$url=$row['url'];
$title=$row['title'];
$summary=$row['summary'];
$coverage=$row['coverage'];
$format=$row['format'];
echo <<<HTML
<p><h6>$title</h6>
<br />$summary</p>
HTML;
}
mysqli_close($con);
the first serious problem with this script is that it seems to be prone to MySQL Injection, the most serious problem of them all. (but I may be wrong). Please consider switching this code to PDO and its prepared statements and bindParam method.
the second is that, in the FORM you either support search OR letter (but not both)
BUT you use both in mysql query.
you should split the result fetching from
$result = mysqli_query($con,"SELECT
title,summary,url,coverage,format,fletter
FROM dbs
where title like
'%$search%' or summary like '%$search%' or fletter = '$searchletter'");
into if/else statement:
if(!empty($search)){
$result = mysqli_query($con,"SELECT
title,summary,url,coverage,format,fletter
FROM dbs
where title like
'%$search%' or summary like '%$search%'");
} elseif(!empty($searchletter)){
$result = mysqli_query($con,"SELECT
title,summary,url,coverage,format,fletter
FROM dbs
where fletter = '$searchletter'");
}
this will not fire BOTH cases on the search and should return more reliable result based on your selection.
EDIT: after you added more code, it's clear that every "unset by user" field has value of "default". which means:
whatever letter you chose, the "seachphrase" will be set to "default" and "default" appears to be a part of FT.com summary field (you can see this word in search results). Again: splitting the query into two cases will solve this, so "default" word is never used in the search query.
I have code for a search function here:
<?php
include("config.php");
$search = mysql_real_escape_string($_POST['search']);
if (!empty($_POST['search'])) {
$data = mysql_query("SELECT * FROM shop WHERE name LIKE '%$search%' OR shout LIKE '%$search%' ORDER BY id DESC ") or die(mysql_error());
while ($info = mysql_fetch_array($data)) {
$name = stripslashes($info['name']);
$shout = stripslashes($info['shout']);
//Result code goes here eventually
}
}
?>
and I'll eventually make it display all results in a grid.
My problem starts when a user clicks on an item to see a page devoted to just that item (like any retail store site).
I'm assuming in my search code I can use $_SESSION and just set all the columns to sessions and then echo them on my results.php page.
Is this an efficient way to do this or am I going about it wrong?
I see websites that when you click on a certain item the URL looks all crazy and what not and I'm not really sure what causes that.
You can use
header('Location: /search/'.rawurlencode($search));
exit;
and now you can get your search string by
$search = rawurldecode($_GET['your_name']);
and your first page will not differ from the others. Or you can use method="get" in your search form. Anyway, you can use session to store your search string.
im creating a website and within the website there will be a search box that will let you search for items on your website. I have code but i keep getting an error message.
<?php
include 'connect.php';
$search = $_POST['search']."*";
$search_query = $link->prepare("SELECT name FROM products WHERE MATCH(name)
AGAINST (? IN BOOLEAN MODE)")
$search_query->bind_param('s', $search);
$search_query->execute();
$search_query->store_result();
$search_rows = $search_query->num_rows;
$search_query->bind_result($product_name);
if($search_rows > 0){
while($search_query->fetch()){
echo "Your search returned $search_rows results";
echo $product_name."<br>";
}
} else { echo "Your search returned no results, sorry :("; }
is it possible to run a search using a mysql query from the database to return searches??
Any advice would be deeply appreciated.
Thanks
The error is most probably because of your syntax.
$search_query->store_result();
$search_rows = $search_query->num_rows;
$search_query->bind_result($product_name);
Here, you are first trying to store the results and later binding the results to variable $product_name which leads to the said error.
The bind_result states:
Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
That code needs some work.
That loop looks flawed. Try something like this:
echo "Your search returned $search_rows results";
while($search_query->fetch()){
echo $product_name . "<br>";
}
I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';