I have a PHP search script that searches a MySQL database to answer questions. Currently my database is set out like this...
idquestion = what is the timeanswer = The time is 12:00
This data is then sent to my PHP code:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM questions WHERE `question` LIKE '%{$query}%' LIMIT 1";
$searchResult=mysql_query($searchSQL);
while($row=mysql_fetch_assoc($searchResult)){
$results="{$row['answer']}";
}
echo $results;
}
?>
Currently, the users query must contain exactly the same text as the question field. My question is; how can I make this work so it triggers a certain for several keywords?
I hope you can understand my question
I think full test search index can help
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html SOUNDEX function can be useful in this context too.
You can split query to keywords and generate dynamic SQL but it is inefficient (performance issues SQL injection attacks ) see http://php.net/manual/en/function.split.php
Alternative is to add table QUESTION_KEYWORD(QUESTION_ID,KEYWORD), split question and search this table to find best QUESTION_ID, but full text search index is more efficient. In fact full text search index uses similar data structure to optimize test search.
For an easy quick-fix based on your comment you could do something as simple as this:
// Assuming query string is ?q=make,sponge,cake
$searchSQL="SELECT * FROM questions WHERE ";
$count = 0;
foreach (explode(',', $_GET['q']) as $query) {
$searchSQL .= "`question` LIKE '%" .mysql_real_escape_string(trim($query)) . "%' ";
if ($count++ > 0) {
$searchSQL .= ' OR ';
}
}
$searchSQL .= ' LIMIT 1';
$searchResult = mysql_query($searchSQL);
Related
I've been using the function LIKE in this statement however its not doing what I expected for it to do, Basically a user on my site has a subject which usually looks like this hello welcome to my #room hows it going #fun and what im using is the LIKE function to select all users with the subject containing #fun my statement looks like this;
$search = 'fun';
$sql = "SELECT * FROM `usr_users` WHERE `subject` LIKE '%$search%'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['username'];
}
however when the query runs it only selects the users which have fun at the begining of their subject or not at all. is there a different function I can use to select words from within in the subject not just the first word.
You also need a % at the beginning of the string to search.
$sql = "SELECT * FROM `usr_users` WHERE `subject` LIKE '%$search%'";
--- UPDATE ---
It may be failing you because you may need to escape the data. check for errors mysql_error() against your query. It might be throwing you something about it. mysql_real_escape_string(). That # could be the culprit if it's part of your actual query. Or use htmlspecialchars() or something like that to echo out the query.
I am trying to create a search blog system where blogs are displayed based on user suggestions. Suggestions are basic hashtags which is stored in user_information table. While blogs will also have some hashtags input by blogger which will be stored in blog table.
Now as I have to match hashtags from user_information table to blog table, I am not finding a way to do this.
I have tried mysql LIKE CLAUSE but I am not able to get even single result.
My Query was [just representation]
SELECT * FROM blog WHERE hashtags LIKE $hashtags_from_user
You are not correctly escaping the value, you require the hash tags to be enclosed in quotations
"LIKE '". $hashtags_from_user ."'";
Additionally you will pay the price in the SELECT statement when you have denormalized database (hash-tags should have their own row in a hash_tags table and the blog would references these via a many-to-many or many-to-one association)
Currently the output of the query is:
SELECT * FROM blog WHERE hashtags LIKE '#hashtag1,#hashtag2,#hashtag'
This isn't going to give you the results you want if you need to match on the individual tags.
The only soultion would be to read the users has tag string, break it up into each tag (using $tags = explode(',', $hash_tags_from_user); and then build up a query to include all of them
$where = array();
$select = 'SELECT * FROM foo';
foreach($tags as $tag) {
$where[] = sprintf('tag LIKE \'%s\'', $tag);
}
if (! empty($where)) $select .= 'WHERE ' . implode(' OR ', $where);
Please don't use the above as it's just and example (and open to simple SQL injection) consider using prepared statements, with PDO/MySQLi.
Try this:
$sql = 'SELECT * FROM blog WHERE hashtags LIKE "'.$hashtags_from_user.'";';
You have to put the string you are searching for between ' or " you can do it without only with numbers.
I have a HTML form that people can select some or all off to search a database for member profiles.
Some of the options are:
Male/Female
Age
Location
check boxes like intentions or interests
etc
I need to tailor a MySQL query to meet the selection the member has chosen.
I'm asking because I built a custom search like this before and it turned into a complete mess with multiple queries depending on what was selected.
Would it be best to just build one query and have parts that are added depending on what is selected?
Does anyone have a ruff example?
Database Schema:
I have a number of tables with the related information so I would need to use joins. That said everything works on one primary key PID so it would all join on this.
You could do something like this:
<?php
$whereClause = '';
if($_GET['gender'] == 'male'){
$whereClause .= ' AND gender = "M"';
}
if($_GET['age'] != ''){
$whereClause .= ' AND age = "'.$_GET['age'].'"';
}
?>
I would use an array:
$where = array();
if($_GET["gender"]!=""){
$clean = mysqli_escape_string($db, $_GET["gender"]);
array_push($where, "gender = '$clean'");
}
// etc...
$where = implode(" AND ", $where);
$sql = "SELECT * FROM table WHERE $where";
I have a database of about 3000 books and i want to be able to search my database for books either by titles, subjects or authors.. I've done my best trying to write a script using php and mysql but i still didn't get it right. can anyone assist please. Below is how far I've come with the script.. and an example of the table in my mysql database
<?php
if (#$find == "")
// Otherwise we connect to our Database
mysql_connect("localhost", "root", "erhun") or die(mysql_error());
mysql_select_db("books") or die(mysql_error());
// We perform a bit of filtering
#$find = strtoupper($find);
#$find = strip_tags($find);
#$find = trim ($find);
#$search = strip_tags(stripslashes(mysql_real_escape_string(#$db, #$_POST["search"])));
//query the database
#$query = ("SELECT * FROM `project` WHERE (`author1` LIKE '%$search%' OR `main_title` `LIKE '%$search%' OR `subj1` LIKE '%$search%')");
//displaying the data
#$results=mysql_query(#$query) or die(mysql_error ());
if(mysql_num_rows(#$results) >= 1)
//here the table starts
echo "<table id='results'>";
while($row=mysql_fetch_array($results))
{
echo "<tr><td><img src='image1/".$row['image']."' height='100px' width='90px'></td><td valign='top'>
<b><a href='details.php?id=".$row['book_id']."'>".$row['main_title']."<br/>
By: ".$row['author1']."</a></b><br/>
<b>Call no:</b> ".$row['call_no']."<br/>
<b>Type:</b> ".$row['item_type']."<br/>
<b>Year:</b> ".$row['publdate']."</td></tr>";
}
echo "</table>";
?>
my table contains these different fields
Full texts
book_id
image
main_title
author1
call_no
item_type
publdate
publplace
publshr
item_home
item_status
subj1
subj2
Try like
#$query = "SELECT * FROM `project` WHERE (`author1` LIKE '%$search%' OR `main_title` LIKE '%$search%' OR `subj1` LIKE '%$search%')";
You have an extra quote ` after "main_title"
UPDATED :
Try changing this line :
#$search = strip_tags(stripslashes(mysql_real_escape_string($db, #$_POST["search"])));
to :
#$search = strip_tags(stripslashes(mysql_real_escape_string( #$_POST["search"])));
The only thing I needed to change was dropping the $db variable, just passing in the search string, and it seems to work fine. It might be that $db was needed for some other reason so I recommend going back to the documentation you got that from and investigate further.
P.S. I'd still recommend using MATCH AGAINST. If your subject, title and author fields have an appropriate FULLTEXT index you can use MATCH AGAINST e.g. :
#$query = "SELECT * FROM `project` WHERE MATCH (subj1, main_title, author) AGAINST ('$search' IN NATURAL LANGUAGE MODE)";
This query would require that you have a fulltext index over all three columns:
ALTER TABLE project ADD FULLTEXT(subj1, main_title, author);
The list of columns in the index must match the list of columns you want to MATCH AGAINST in the query for the sake of optimisation I believe. You'd have to create other indexes if you wanted to be able to match against individual columns separately. That query also worked on my test page and it should better support normal search queries with a bit of experimentation.
P.P.S. If you have a choice of DB I would recommend using something with more support for different types of text searching. The only relational databases I'm really familiar with are PostgreSQL and MySQL and PostgreSQL has a lot better support for text searching.
I am trying to make a search program. I have three tables: postivewords, negativewords and recommendationwords. These tables consist only of word_id then the word. How I do it in a query? This is what I have so far. Please correct me if I am wrong.
if(isset($_POST['searchword']))
{
$word = $_POST['search'];
$search1= mysql_fetch_array(mysql_query("SELECT * FROM positivethesaurus where word like '%$word%'"));
$search2= mysql_fetch_array(mysql_query("SELECT * FROM negativethesaurus where word like '%$word%'"));
$search3= mysql_fetch_array(mysql_query("SELECT * FROM recommendationthesaurus where word like '%$word%'"));
}
select * from negativethesaurus, positivethesaurus,recomendationthesaurus where negativethesaurus.word like '%"word%' or positivethesaurus.word like '%word%' or recomendationthesaurus.word like '%word%';
This may be not the fastest way (you would use indexes and freetext) but it will be down on only one query.
Oh yes, that been said this query is vulnerable to sql injection attacks.
also do mysql_escape_string to avoid sql injection
$word = $_POST['search'];
$word = mysql_escape_string($word);
$query = SELECT positivethesaurus .*,negativethesaurus.*,recommendationthesaurus.* FROM positivethesaurus,negativethesaurus,recommendationthesaurus where positivethesaurus.word like '%$word%' OR negativethesaurus.word like '%$word%' OR recommendationthesaurus.word like '%$word%'";
UPDATES
if you want to check if results not found then do it like this
<?php
$query = mysql_query("Your Query Here");
$rowCount = mysql_num_rows($query);
if($rowCount>0) {
// DO YOur STUFF IF RESULTS FOUND
} else {
echo "No Results Found";
}
?>
Please not that mysql_* function should not be used
Hope this works. Not Tested though. Let me know if you find any problem
1) Select the respected column instead of select * from
2) avoid sql injection