So i am currently messing around creating a search engine just out of interest and was curious if i was able to query more than just the keyword column in the mysql database. At the moment i am able to search for somthing and get the results based off of my "keyword" column. But if the word or phrase i am searching not within the keyword column but it is found in the title column or description column is it possible for it to show up because it found it within those columns aswell?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Search Engine - Search</title>
</head>
<body>
<h2>Search Engine</h2>
<form action='./search.php' method='get'>
<input type='text' name='k' size='50' value='<?php echo $_GET['k']; ?>' />
<input type='submit' value='Search'>
</form>
<hr />
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM databeast WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
//connect
mysql_connect("localhost", "username", "password");
mysql_select_db("fapster") or die(mysql_error());
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)){
$url = $row['url'];
$title = $row['title'];
$keywords = $row['keywords'];
echo "<h1><a href='$url'>$title</a></h1>
$keywords<br /><br />";
}
}
?>
</body>
</html>
Thanks in advance
I suggest you check into MySQL Full-Text search. http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html.
This allows you to search multiple keywords in a query. Plus, Full-Text gives you the benefit of actually understanding the words as "natural language" (so it deals with "stop words", "plurals" and "word stemming"). See http://dev.mysql.com/doc/refman/5.0/en/fulltext-query-expansion.html
Don't throw out the "Like" logic. MySQL Full-Text search has a few annoying things - so you may still want to use that logic. Here they are:
Searches which return "too many" (%50 or greater) results return nothing. Not what a searcher usually expects, right? Normally people want it to work like Google does.
Searches on words which are too short return nothing (see ft_min_word_len in /etc/my.sql)
Usually I combine the full text search with the like or "or" search and then ORDER by full text rank.
p.s. you'r script is vulnerable with SQL injection. Don't release onto Internet before reviewing.
Related
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search Engine Project</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form action="action.php" method="GET" class="search_form result-form" autocomplete="off">
<span class="result-header">Server Search</span>
<input type="text" name="k" class="input result_input" value="<?php echo $_GET['k'] ?>">
<input type="submit" name="search" value="Search Web" class="search">
</form>
</div>
<script src="js/bootstrap.min.js" ></script>
<script src="js/jquery-3.1.1.min.js" ></script>
<script src="js/javascript.js"></script>
</body>
</html>
<?php
$q=$_GET['k'];
if(isset($_GET['search'])){
header("Location:https://www.google.co.in/? gfe_rd=cr&ei=oyBmWN3FNvPx8Afe7a7IDA&gws_rd=ssl#q=$q");
}
if(isset($_GET['image'])){
header("Location:https://www.google.co.in/search? site=&tbm=isch&source=hp&biw=1280&bih=670&q=$q");
}
if(isset($_GET['video'])){
header("Location:https://www.google.com/search? q=$q&biw=1280&bih=670&tbm=vid&source=lnms&sa=X&ved=0ahUKEwiJ_ruKxpvRAhVFgI8KHeVRBK4Q_AUICigD&dpr=1");
}
if(isset($_GET['local'])){
mysql_connect("localhost", "root", "");
mysql_select_db("search_query");
$k = $_GET['k'];
if($k == "") {
echo "";
}
else {
$terms = explode(" ", $k);
$query= "SELECT * FROM search_table WHERE ";
foreach($terms as $each)
{
$i=0;
$i++;
if($i==1)
{
$query .= "keywords LIKE '%$each%' ";
}
else
{
$query .= "OR keywords LIKE '%$each%' ";
}
}
//query
$query=mysql_query($query) or die(mysql_error());;
$numrows= mysql_num_rows($query);
if($numrows>0)
{
while($row = mysql_fetch_assoc($query))
{
$id= $row['id'];
$title= $row['title'];
$description= $row['description'];
$keywords= $row['keywords'];
$link= $row['link'];
echo "<div style=''><h2><a href='$link'>$title</a></h2>
$description</div> <hr><br/> <br/>";
}
}
else
{
echo"No results found for \"<b>$k</b>\"";
}
//disconnect
mysql_close();
}
}
?>
The above is the php code and the code searches the database in the mysql db and displays the approtiate result........
But when in the home page where i type the required keyword with lots of space before it and press search it gives a error type message :
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'keywords LIKE '%%' keywords LIKE '%%' keywords LIKE '%%'
keywords LIKE '%%' keyw' at line 1 error"
I dont know what to do . I googled a lot in search for the fix.....
Images
PHP Error:
Blank Space input:
Your query failed because of blank values in LIKE clause.
E.g. if user entered book cover
Your existing query will look something like this:
SELECT *
FROM search_table
WHERE keywords LIKE '%%'
OR keywords LIKE '%%'
OR keywords LIKE '%%'
OR keywords LIKE '%%'
OR keywords LIKE '%book%'
OR keywords LIKE '%%'
OR keywords LIKE '%cover%'
To fix this, trim value $_GET['k'] first.
$k = trim($_GET['k']);
Then, filter out blank values in case user adds multiple spaces in between words.
$terms = explode(" ", $k);
$terms = array_filter($terms);
Now, your query will be
SELECT *
FROM search_table
WHERE keywords LIKE '%book%'
OR keywords LIKE '%cover%'
The error you are getting is due to the fact that the OR is not being included in your SQL query. Hence the SQL in the error is keywords LIKE '%%' keywords LIKE '%%' keywords LIKE '%%' keywords LIKE '%%' (no ORs). The reason for this is that you are setting $i=0 just before $i++ in your loop. Thus $i is always 1 and the string with the OR included is never appended. Set $i=0 outside the loop.
The error message came because $i=0; is inside the loop. Move it outside.
Also avoid using blank strings.
Here's what I find a better way to build a WHERE clause:
$ors = array();
foreach ...
{
if (...)
$ors[] = 'keywords LIKE ...'
}
$or_str = implode(' OR ', $ors);
I find that simpler than special-casing the first or last item in an OR or AND list.
Meanwhile, you should consider using FULLTEXT instead of a bunch of LIKEs.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Am a student and novice to the domain of PHP (I have no idea on it). I have assigned a small task of creating a search engine of the website. (I have edited my code based on suggestions)
I have written the following code by searching the google and various forums.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.W3.org/TR/xhtml/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Results </title>
</head>
<body>
<center>
<h1 style="color:#09F; font-size:36px;"> Search </h1>
<form action="./results.php" method="get">
<input type="text" name="input" size="50" value='<?php echo $_GET ['input'];?>' />
<input type="submit" value="search" />
</form>
</center>
<hr/>
<?php
$input = $_GET['input'];
$terms = explode(" ", $input);
$query = "SELECT * FROM search WHERE ";
$first = true;
foreach ($terms as $each) {
if ($first) {
$query .= "keywords LIKE '%$each%' ";
$first = false;
}
else {
$query .= "OR keyword LIKE '%$each%' ";
}
}
//Connect to Database
mysql_connect("localhost","root","");
mysql_select_db("databasem") or die ("database not found");
$query = mysql_query($query);
$numrows = mysql_num_rows($query) or die ("Here's the error");
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href='$link'>$title</a></h2>
$description<br/><br/>";
}
}
**else
echo "No result found for \"<b>$input</b>\"";**
//Disconnect
mysql_close();
?>
</body>
</html>
Am getting the error in line where it is marked bold. mysql is showing that the query is wrong.
I searched google and I found the answers that PHP is using Mysqli instead of Mysql.
I have no idea on it. I found some materials and I was unable to understand it.
It seems to be a silly/useless question for you (experts) but as per my standards and experience this problem hurts me a lot.
---------------------------(Here Comes the points after updating the code)------------
After updating the code everything is going fine when searching but the last else Statement is not runnning. When we searches for the Name which is not located it is not displaying any results instead of displaying "No results found for $Input string".
Can anyone guide me over here please
Thanks
Main problems:
1) Bad variable:
$query .= "keywords LIKE '%each%' ";
^---missing $
since there's no $, you're searching for the literal characters e, a, c, h.
2) Assuming your query can never fail:
$query = mysql_query($query);
^---no error handling
You check for failure on connection and the num_rows call, but not on the most important part: the actual query. Try
$query = mysql_query($query) or die(mysql_error());
3) Vulnerable to sql injection attacks
4) Using the obsolete/deprecated mysql_*() function library.
Your error is in the foreach part, you never increment the $i, so it stays at 0.
This will make the query incorrect because it always picks the if part and not the else part
You also define the $i in the foreach so it will get created each time. It should be on the outside and on the inside of the loop should be $i++ (to increment the $i)
Syntax
$first = true;
foreach ($terms as $each) {
if ($first) {
$query .= "keywords LIKE '%$each%' ";
$first = false;
}
else {
$query .= "OR keyword LIKE '%$each%' ";
}
}
Using mysql is deprecated in current versions of php so you should upgrade to mysqli or PDO where you can also use prepared statements for preventing sql injection.
But maybe that is not necessary for your school project
I'm learning PHP and working on a project for searching books in a MySQL database. The user should be able to search by Book Title, Book Author and by the Category, using all, one or any combination of the 3.
At present here is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to Library Management System</title>
<link href="main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
require_once "db.php";
include "header.html";
if(isset($_POST["bookTitle"]))
{
$bookTitle = mysqli_real_escape_string($con, $_POST["bookTitle"]);
}
else
{
$bookTitle = NULL;
}
if(isset($_POST["bookAuthor"]))
{
$bookAuthor = mysqli_real_escape_string($con, $_POST["bookAuthor"]);
}
else
{
$bookAuthor = NULL;
}
if(isset($_POST["category"]))
{
$category = mysqli_real_escape_string($con, $_POST["category"]);
}
else
{
$category= NULL;
}
echo "Results by Book Title Search";
$bookTitle = mysqli_real_escape_string($con, $_POST["bookTitle"]);
$query = "Select * From book NATURAL JOIN category where category.CategoryDesc LIKE '%" .$category ."%' OR book.BookTitle LIKE '%" .$bookTitle ."%' OR book.Author LIKE '%" .$bookAuthor."%'";
$result=mysqli_query($con, $query) or die(mysqli_error());
echo '<table border="1" width="95%">'."\n";
echo "<tr><th>ISBN</th><th>Title</th><th>Author</th><th>Edition</th><th>Year</th><th>Category ID</th><th>Reserved</th><th>Reserve?</th><tr>";
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<tr><td>";
echo(htmlentities($row[0]));
echo("</td><td>");
echo(htmlentities($row[1]));
echo("</td><td>");
echo(htmlentities($row[2]));
echo("</td><td>\n");
echo(htmlentities($row[3]));
echo("</td><td>\n");
echo(htmlentities($row[4]));
echo("</td><td>\n");
echo(htmlentities($row[5]));
echo("</td><td>\n");
echo(htmlentities($row[6]));
echo("</td><td>\n");
echo('Edit
/ ');
echo('Delete');
echo("</td></tr>\n");
}
echo "</br>";
If I search using all three fields, the query returns the relevant results. If one or more of the fields is left blank, the entire database is returned, which is not what i want.
Is there a better approach to this?
you can use this
$condition="sasaaa";
$bookTitle=trim($_POST['bookTitle']);
$bookAuthor=trim($_POST['bookAuthor']);
$category=trim($_POST['category']);
if(isset($bookTitle))
$condition="booktitle=$bookTitle";
if(isset($bookAuthor))
$condition="bookAuthor=$bookAuthor";
if(isset($category))
$condition="category=$category";
and use this $condition variable in your SQl. use mysqli_real_escape_string().
Hope it will help you :)
It would be better to skip all your tests at the beginning, and simply build your query dynamically, only putting where conditions when your post variables are set. But if you wish to keep this logic (which isn't too good) , just replace your NULLvalues with empty string, and that should do the trick...
I am doing an exercise from the book PHP & MYSQL in easy steps. It involves an HTML form to update a row in a database then various PHP scripts to check the the input data for HTML code and make it into a secure format. However, the code just does not work the way the book says. I went to the publisher's website and downloaded the code example, but no joy.
Instead of a form with the name of the row below it, instead I get the form, then below that "No valid new name submitted". Then below that the current name of row in the table which I want to change. When I try to enter and submit data into the form it makes no difference. It displays exactly the same page. The code is below.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ensuring security
</title>
</head>
<body>
<form action="secure.php" method="POST">
<p>New Name : <input type="text" name="name">
<input type="submit"></p></form>
<?php
require('../connect_db.php');
if (!empty($POST['name']) && !is_numeric($_POST['name'])) {
$name = $POST['name'];
$name = mysqli_real_escape_string($dbc, $name);
$name = strip_tags($name);
$q = 'UPDATE towels SET name "' . $name . '" WHERE id= 1';
mysqli_query($dbc, $q);
} else {
echo 'No valid new name submitted';
}
$q = 'SELECT * FROM towels WHERE id = 1 ';
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo "<p>Name : $row[1] </p>";
}
mysqli_close($dbc);
I'd appreciate any ideas on this. I have spent about 3 hours and been on the publishers website, but I am still at square one.
There is no superglobal array $POST so you have to change $POST['name'] to $_POST['name'].
PHP can't see that array so it evaluates !empty($POST['name']) as false and never executes code with update query.
And, like #BartFriederichs said, buy better book. I don't think you'll learn something valuable from current one.
what is the best, tidiest way to populate a html select tag with items from the database?
For example, if I have the following php:
$sql="SELECT a.athleteId, a.fName, a.lName FROM Athletes a, SupportStaff s, StaffAthletes sa WHERE sa.staffId = $id AND a.athleteId = sa.athleteId";
$result=mysql_query($sql);
Then:
How do I populate the drop down menu with the list of tuples retrieved from the relation?
How should the php, html and jQuery be integrated?
I have the following, but it doesn't work- It just displays a blank page:
<?php
error_reporting(E_ALL)
session_start();
//connect to database
function connect() {
$dbh = mysql_connect ("localhost", "d", "a") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
if(isset($_SESSION['username'])){
$dbh = connect();
$id = $_SESSION['id'];
$sql="SELECT a.athleteId, a.fName, a.lName FROM Athletes a, SupportStaff s, StaffAthletes sa WHERE sa.staffId = $id AND a.athleteId = sa.athleteId";
$result=mysql_query($sql);
$options="";
$i = 1;
while ($row=mysql_fetch_array($result)) {
$f=$row["fName"];
$l=$row["lName"];
$options.="<OPTION VALUE=\"$i\">".$f.' '.$l."</OPTION>";
$i++;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#go").click(function(e){
if($("#selectathlete option:selected").val() == "0"){
alert("Please Select An Athlete");
}else{
//set hidden textfield
$("form#profile").submit();
}
});
});
</script>
<title>Personal Diary System - Home Page</title>
</head>
<body>
<h1>Home Page</h1>
<p>Select An Athlete:
<SELECT ID ="selectathlete" NAME="athletes">
<OPTION VALUE="0">Choose</OPTION>
<?php echo($options);?>
</SELECT>
</p>
<form id = "profile" name="input" action="viewathleteprofile.php" method="post">
<input type = "hidden" id = "athleteId">
<input type = "button" name = "go" id = "go" value = "Go">
</form>
</body>
</html>
I've been debugging for hours and it just doesn't work...
You should try to error_reporting(E_ALL) your page, so that you can see any and all errors your page comes across.
What's connect()? did you mean mysql_connect()?
(Kinda unrelated) You shouldn't use mysql_* functions, use MySQLi (Good) or PDO (Awesome).
when i get stuck on server 500 errors i go over to http://phpcodechecker.com/ and paste in the page. when i did that on what code you have now, it complained about a missing ; on line 2.
another tip: you can use this syntax style for slightly less complex output:
$out = "text {$var} {$var2} {$array['index']}".DEFINITION_ONE
surprisingly this works for html attributes which we expect to output as "value" e.g.
$options .= "{$i} {$f}
make sure your file is a .php, not .html
don't forget "<?php" at the top of page.
try to write "echo 'hello';" at the top your page to see if it prints.
this seems trivial, but as you seem to have pasted the full code, i just wanted to make sure.
Perhaps $_SESSION['username'] isn't set? You don't have a closing brace on that if statement, so if isset($_SESSION['username']) returns false, the whole page never gets displayed.