This question already exists:
PHP KEYWORD SEARCH ENGINE NO RESULTS [duplicate]
Closed 7 years ago.
I have a simple MySQL database keyword search that is functional. However results for the search are not being returned if the keywords are not in the same order as entered in the database. For example searching for "dog cat lion" will return a result, but searching for "dog lion cat" will return no results.
Any help on how to fix this issue would be greatly appreciated. Here is my code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Part Search</title>
</head>
<body>
<?php
$username = "xxxx";
$password = "xxxx";
$hostname = "localhost";
//connection to the database
mysql_connect($hostname, $username, $password);
mysql_select_db("wesco");
$search = mysql_real_escape_string(trim($_POST['searchterm']));
$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%'");
while($row = mysql_fetch_assoc($find_parts))
{
$name = $row['name'];
echo "$name<br />";
}
?>
</body>
</html>
You could use something like this
$searchArray = explode(" ", $_POST['searchterm']);
$query = "";
foreach($searchArray as $val) {
$search = mysql_real_escape_string(trim($val));
if (!empty($query)) {
$query = $query . " OR "; // or AND, depends on what you want
}
$query = $query . "`keywords` LIKE '%$search%'";
}
if (!empty($query)) {
$find_parts = mysql_query("SELECT * FROM `parts` WHERE $query");
}
Also, you should stop using the mysql_* functions and start using the object oriented implementation of mysqli.
You need to order your Query.
if you have an auto_incremented Id you could go:
$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%' ORDER BY row_id asc");
you can order by Name or really anything:
$find_parts = mysql_query("SELECT * FROM `parts` WHERE `keywords` LIKE '%$search%' ORDER BY name asc");
Two options:
use the build in mysql search functionality.
https://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html
this is probably the better solution.
if you want to continue to use LIKE, then split the words as follows.
select *
from parts
where
(
keywords LIKE '%$word1%'
AND
keywords LIKE '%$word2%'
AND
keywords LIKE '%$word3%'
)
Related
I'm trying to get all the rows which contain a particular text. However, when I execute the query, no rows are returned. I'm retrieving the text from a post request which looks like this "Krachttraining,Spinning" (= 2 values). I think my code fails on the following part (if I leave this out, the query returns some rows): AND CONCAT('%', sport.name, '%') LIKE $sports.
FYI. I know you can perform SQL injection on this, this will be fixed later.
<?php
$servername = "SECRET";
$username = "SECRET";
$dbpassword = "SECRET";
$dbname = "SECRET";
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$sports = $_POST['sports'];
echo $sports; //Echo's: Krachttraining,Spinning.
// Create connection.
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
// Check connection.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND CONCAT('%', sport.name, '%') LIKE $sports";
$result = $conn->query($sql);
$output = array();
if ($result->num_rows > 0) {
// output data of each row.
while($row = $result->fetch_assoc()) {
$id = $row["id"];
array_push($output, $gym);
}
//Brackets because of GSON's parser.
echo "[" . json_encode($output) . "]";
}
$conn->close();
?>
EDIT: Changed SQL statement to:
$sql = "SELECT * FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports."%'";
Still getting 0 rows returned.
EDIT 2: I ran the following code in my phpMyAdmin environment, and it returned 0 rows.
Select * FROM sport WHERE name LIKE '%Krachttraining,Spinning%';
However when I'm running the following code, it returns 1 row:
Select * FROM sport WHERE name LIKE '%Krachttraining%';
I don't really get it what I'm doing wrong, any thoughts?
I think you want to use the IN statement.
This will check if any word in the array matches. For instance:
Select * FROM sport WHERE name IN ('Spinning', 'Krachttraining'); Will return every row which has the name Spinning or Krachttraining.
Just use:
SELECT .FROM...WHERE AND sport.name LIKE '%".$sports."%'";
After question editing
After you changed the question, I suggest to take a look at this answer to better understand what you should to do: https://stackoverflow.com/a/3902567/1076753
Anyway I think that you have to learn a bit about the like command: http://www.mysqltutorial.org/mysql-like/
Change the sql to :
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports%."'";
I am making an electronic health system related to patient diagnosing in PHP and MySQL. I have made following tables in database with the following records:
Illness(illness_id(PK), illness_code,illness_name)
Symptom(symptom_id, illness_id(FK),symptom_name ).
Now, what I would like to do is that, I will write name of symptom in search bar and after clicking button, related diseases should be output. Could you tell me SQL query that will output appropriate diseases please?
Please try this. After you retrieve the symptom value from the search bar into a variable, say symptom_name_provided_in_search_bar, you can use that value in the below query
select illness_name
from illness a, symptom b
where a.illness_id = b.illness_id
and b.symptom_name = :symptom_name_provided_in_search_bar
For this to work you should create only one table illness with 2 rows:
illnessName and illnessSymptom. Note: This will only work if the symptom is written exactly as in the database.
<?php
$host = 'yourmysqlhost';
$user = 'yourmysqluser';
$pass = 'yourmysqlpassword';
$db = 'yourmysqldatabase';
$symptom = $_POST['symptom'];
$connect = mysqli_connect($host, $user, $pass, $db);
$sanitizedSymptom = mysqli_real_escape_string($connect, $symptom);
$query = mysqli_query($connect, "SELECT * FROM illness WHERE illnessSymptom = '".$sanitizedSymptom."'");
if(mysqli_num_rows($query) == 0)
{
echo '<p>No results...</p>';
}
else
{
while($row = mysqli_fetch_assoc($query))
{
echo '<h1>'.$row['illnessName'].'</h1>';
echo '<p>Symptom: '.$row['illnessSymptom'].'</p>';
echo '<br>';
}
}
?>
Edit:
To find a symptom that is approximately like the symptom in the database, the query should be like this:
$query = mysqli_query($connect, "SELECT * FROM illness WHERE illnessSymptom LIKE '%".$sanitizedSymptom."%'");
I am trying to allow users to search a database and echo results, the thing is I want to search multiple tables. I know I can do SELECT * FROM x1, x2 but the rows are named something else so I cant
echo $row['username']
when the other row is username2. Maybe if its possible something like if($row == whatever), idk. Thanks for any help.
<?php
$search = $_POST['Srch'];
$host = "whatever";
$db = "whatever";
$user = "whatever";
$pwd = "whatever";
$link = mysqli_connect($host, $user, $pwd, $db);
$query = "SELECT * FROM users WHERE email LIKE '%$search%'";
$results = mysqli_query($link, $query);
if(isset($_POST['Srch'])) {
if(mysqli_num_rows($results) >= 0) {
while($row = mysqli_fetch_array($results)) {
echo "Username: " . $row['username'];
echo "Email: " . $row['email'];
}
}
}
?>
<body>
<form action="" method="POST">
<input type="Text" name="Srch">
<input type="Submit" name="Submit">
</form>
Edit: Found a way to do this. Something like this works:
function search1() {
// Search stuff here
}
function search2() {
// Search more stuff here
}
if(isset($_POST['Srch'])) {
search1();
search2();
}
If you want to search multiple tables you're going to have to join them somehow. Since you didn't post your table structure, I can only make assumptions on what you're trying to do, but the general syntax would be:
$query = "SELECT * FROM users u LEFT JOIN something s ON s.id = u.something_id WHERE u.email LIKE '%$search%'";
Then you can echo out the different columns that return. But again, this question needs more information for a better answer.
Hope this helps anyway!
I have a MySql DB and in the Table 'Klant' I have the column names:
ID
Naam
Email
Soort
Status
I get the column names with this query:
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";
And I am selecting the data from the Table with this simple query:
$strSQL1 = "SELECT * FROM NAW.Klant";
What I want to do is search a text and with str_replace I want to replace the column_names with the data from the DB. For example:
If I type in Hello Naam, your email adress is Email I would want it to display Hello Robert your email adress is robert#gmail.com. And I will put that in a loop to do it for every row. I am currently using this:
$ID = $row['Klant_ID'];
$Naam = $row['Naam'];
$Email = $row['Email'];
$Soort = $row['Soort'];
$Naam = $row['Status'];
$vaaw = array("[ID]","[Naam]", "[Email]", "[Soort]", "[Status]");
$vervang = array("$ID","$Naam", "$Email", "$Soort", "$Status");
echo str_replace($vaaw, $vervang, $message);
The reason I do not want to use this anymore is because if I ever need to change/add/delete a column the code would still work. (I know it is a bad idea to change columns but you never know.) And also this code will work with other Tables/DB's to.
I have tried loads of things to get this to work but I just haven't got a clue how to do this and it has been bugging me for almost 2 days now. If someone knows a function or a way to do this it would be very helpful!
Try this:
<?php
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";
$con=mysqli_connect('host', 'username', 'password', 'db');
if(!$con){
//error
}
$result=mysqli_query($con,$strSQL);
if(!$result){
//error
}
$table_columns=array();
//$row=mysqli_fetch_assoc($result);
while($row=mysqli_fetch_assoc($result))
{
$table_columns[]=$row['column_name'];
}
$query="select * from NAW.Klant "; //limit 10";
$result=mysqli_query($con,$query);
if(!$result){
//error
}
$greeting_text="";
while($row=mysqli_fetch_assoc($result)){
$greeting_text.= (isset($row['naam']))? "Hello {$row['naam']}":""; // because you want the 'hello'
for($i=1;$i< count($table_columns);$i++){
$greeting_text.=" Your ".$table_columns[$i]." is ".$row[$table_columns[$i]].", ";
}
$greeting_text.="\n";
}
echo $greeting_text; //test your result
If you have a predefined string template (to be replaced by column names or their values), you need to change that code when there is any change in the table columns. I simply choose to dynamically generate the string depending on the availability of columns. But if you need to use a predefined string, it is not difficult to do so.
I solved it using the script that HamZa linked in the comments. Since he is not posting it as an answer I will do it myself because I think it could help others.
The code that solved the problem is this:
$connection = mysql_connect('localhost', 'root', 'pw') or die('couldn\'t connect to the database.<br>'. mysql_error());
mysql_select_db("NAW");
$strSQL1 = "SELECT * FROM Klant";
$result = mysql_query($strSQL1, $connection) or die('Something went wrong with the query.<br>'. mysql_error());
while($row = mysql_fetch_assoc($result)){
$text = $_POST['naam'];
foreach($row as $k => $v){
$text = str_replace('['.$k.']', $v, $text);
}
echo $text;
echo "<br>";
}
Hi I am trying to get a search working for a site. It has 2 inputs for taking in info, one is a dropdown.
<div id="search">
<form action="projectsearchall.php" method="post" enctype="multipart/form-data">
<h3>Search for an Item</h3>
<p>Keywords</p><p><input name="keywords" type="text" value="keywords"></p>
<p>Select A Location</p><p>
<select name="location" id="jumpMenu">
<option>Any Location</option>
<option>Antrim</option>
<option>Armagh</option>
<option>Carlow</option>
<option>Cavan</option>
</select>
</p>
<p>
</form>
</div>
I cannot seem to figure out how to combine the 2 inputs to give a result, I can do it separately, but not working together to get a more accurate result.
php
$keywords = $_POST['keywords'];
$keylocation =$_POST['location'];
$username = $_SESSION['username'];
//MySQL Database Connect
include 'connect.php';
//make sql query
$result = mysqli_query($con,"SELECT * FROM projectitem where description like '%$keywords%' or item like '%$keywords%' or location like '%$keywords%'");
Thanks in advance!
I think you may do some preprocessing, before running your query.
First off, you need to give your select options some sort of value to check against.
I don't know your exact database structure, but assuming that you're working with the select texts, you may want to try this:
$query = "SELECT * FROM projectitem WHERE (description LIKE '%$keywords%' OR item LIKE '%$keywords%')";
This is your base query and running it right now will check against the keywords, but no location.
if($keylocation != "Any location") $query .= " AND location = '$keylocation'";
This last line will add the location as additional filter to your query. Run it, and see what it does. (I'm not sure about the string comparison there though)
Ah yes, as a final advice: Be sure to run your input through the escape function mysqli_escape_string. Otherwise you're opening yourself to SQL injections.
You're not actually using the value of $keylocation; to narrow searches down, you need an AND instead of OR:
$stmt = mysqli_prepare($con, 'SELECT * FROM projectitem
where (description LIKE ? OR item LIKE ?) AND location LIKE ?');
mysqli_stmt_bind_param($stmt, 'sss', "%$keywords%", "%$keywords%", "%$keylocation%");
mysqli_stmt_execute($stmt);
// etc.
Update
Since the drop down may have "any location" you would need to dynamically change your query:
$sql = 'SELECT * FROM projectitem WHERE 1'; // base query
$types = ''; $vars = array();
if (!empty($keywords)) {
$sql .= ' AND (description LIKE ? OR item LIKE ?)';
$types .= 'ss';
$vars[] = "%$keywords%";
$vars[] = "%$keywords%";
}
if ($keylocation != 'Any Location') {
$sql .= ' AND location LIKE ?';
$types .= 's';
$vars[] = $keylocation;
}
$stmt = mysqli_prepare($con, $sql);
if ($types) {
mysqli_stmt_bind_param($stmt, $types, $vars);
}
mysqli_stmt_execute($stmt);
first you have sql injection
use mysqli_real_escape_string
if keywords for example is null your query will be like this
$result = mysqli_query($con,"SELECT * FROM projectitem where description like '%%' or item like '%%' or location like '%$keylocation%'");
and description like '%%' return all row !
you must check data first
$query = "SELECT * FROM projectitem where 1=1 "
if($keywords)
$query .= " AND ( description like '%$keywords%' AND item like '%$keywords%' )";
if($keylocation)
$query .= " AND location like '%$keylocation%'";