I face a problem with the str_replace function, see the code below :
$query = "SELECT title FROM zakov WHERE chnt='$atd_nad'";
$str = str_replace("Example.com_", "","$query");
$result = mysql_query($str) or die('Errant query: '.$str);
What I want is to replace the word " Example.com_ " with nothing "" but it did not work for me ! I do not know why.
In the row 'title' you can find something like this " Example.com_nameofsmthng "
So what I want is to keep just the word "nameofsmthng" and also to keep the begining of each word of it in capital letter to have finally somethin like "NameOfSmthng"
$atd_nad = 'Foobar Example.com_nameofsmthng Bazbat';
$query = 'SELECT title FROM zakov WHERE chnt="' . $atd_nad . '"';
$str = str_replace('Example.com_', '', $query);
echo $str; // SELECT title FROM zakov WHERE chnt="Foobar nameofsmthng Bazbat"
This works fine. Try it quickly. My assumption is that you mistyped $atd_nad or the value is incorrect.
Edit: hmm i think I misunderstood the example your trying to replace the string in the query string instead of the database?
You could make mysql do the replacement for you which should be faster then making php do it.
$query = "SELECT REPLACE(title, 'Example.com_', '') as newtitle FROM zakov WHERE chnt='$atd_nad'";
$resultset = mysql_query($query) or die('Errant query: '.$query);
$result = mysql_fetch_assoc($query);
echo $result['newtitle'];
Or you could replace all occurrences in the database with an update and then just select the title.
UPDATE zakov SET title = REPLACE(title, 'Example.com_', '');
Hope this helps.
while($row = mysql_fetch_assoc($result)) {
$title = str_replace("something", "", $row['title']);
}
Is what I believe you're looking for. Your code is trying to replace it in the query, which doesn't make sense. You need to replace it in the actual records. This will replace "something" with "". Alternatively, if you've already stored them in an an array or something you would just loop over the array and do the replacement. Basically: operate on the records, not on the query.
Related
<?php
include"configration.php";
?>
<?php
$query = $_GET['query'];
$min_length = 1;
//echo $query;exit();
if (strlen($query) >= $min_length) { // if query length is more or equal minimum length then
//echo "success";exit();
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$sql = "SELECT * FROM table2
WHERE title LIKE '%".$query."%' order by date DESC";
$raw_results = mysqli_query($conn, $sql) or die(mysql_error());
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($res = mysqli_fetch_array($raw_results)) { ?>
<?php echo $res['title'] ?> // Place where result comes ..
<?php }
}
}
?>
This is code works fine but search in this way
For Example Title is: you are vary nice boy but lazy
When I search by:
You are vary ............. result shows ..
vary nice boy ............. result shows ..
vary lazy, or boy lazy or vary lazy .. result not shows ..
Plz some one help me in this and how to show searched query in title ..
<title> Searched Query ...</title>
LIKE '%boy lazy%' will show the Of the cases where anything can be before boy lazy and anything can be after boy lazy, but boy lazy will be together.
In your case, one approach can be, you can explode your $query, and then use multiple LIKE queries to create sql query. Example:
<?php
//$conn = mysqli_connect("localhost","your user","your pass","db");
$query = $_GET['query'];
$min_length = 1;
//echo $query;exit();
if (strlen($query) >= $min_length) { // if query length is more or equal minimum length then
//echo "success";exit();
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$searchKeys = explode(' ',$query);
$sql = "SELECT * from table2 where title ";
foreach ($searchKeys as $key) {
$sql.= "LIKE '%".$key."%' AND title ";
}
$sql = substr($sql, 0, -10);
//$sql.="ORDER BY date DESC;";
$raw_results = mysqli_query($conn, $sql) or die(mysql_error());
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($res = mysqli_fetch_assoc($raw_results)) {
echo $res['title']."\n";
}
}
}
When you search title LIKE "%vary lazy%", you will get records that contain the string "vary lazy" preceeded and followed by any other or no character sequences. If you want to match strings that contain the words - I should better say, the character sequences - "vary" and "lazy" in that specific order you should use:
title LIKE "%vary%lazy%"
However, this will also match "varylazy", "varying lazytown characters".
Assuming you generally intend to use queries as you mentioned, i.e. each word is separated by a space character and you want to see if those words appear in a text in specifically that order, you could write something like this:
$query = $_GET["query"];
$query = '%'.str_replace(' ', '%', $query).'%';
//... MySQL stuff
Please be aware that the code above is very specific to your needs. I wouldn't use it as a general purpose approach for processing query strings, e.g. having multiple spaces between words would result in multiple consequent % in your SQL query - I'm not even sure if that is allowed. However, under the constraints described, this code should work just fine.
My code let me perform search, as long as the order of the words is correct.
Let's say I'm searching for big dog, but I also want to search for dog big. It get more complicated with 3 or more words.
Is there a way to create a SQL query which would let me search through values with any order?
Only way I can think of this is by having multiple queries, where I change order of PHP variables manually...
<?php
if(isset($_GET['query']) && !empty($_GET['query'])) {
$query = $_GET['query'];
$query_array = explode(' ', $query);
$query_string = '';
$query_counter = 1;
foreach($query_array as $word) {
$query_string .= '%' . $word . (count($query_string) == $query_counter++ ? '%' : '');
}
$query = "SELECT * FROM pages WHERE Name LIKE '$query_string'";
$result = sqlsrv_query($cms->conn, $query);
while($row = sqlsrv_fetch_array($result)) {
extract($row);
echo ''.$Name.'<br>';
}
sqlsrv_free_stmt($stmt);
}
else {
//echo 'NO GET';
}
?>
You could assemble your conditions and check for each word on it's own:
$query_array = explode(' ', $query);
$queryParts = array();
foreach ($query_arra AS $value){
$queryParts[]="Name like '%".mysql_real_escape_string($value)."%'";
}
$searchString = implode(" AND ", $queryParts);
The Search string would now be Name like '%big%' AND Name like '%dog%' ... depending on how much search-keywords have been there.
I use the same approach very often, also when it is required that ALL keywords appear in at least ONE of the columns. Then you need one more loop to create the required AND conditions:
$search = "Big Dog";
$keywords = explode (" ", $search);
$columns = array("Name", "description");
$andParts = array();
foreach ($keywords AS $keyword){
$orParts = array();
foreach($columns AS $column){
$orParts[] = $column . " LIKE '%" . mysql_real_escape_string($keyword) . "%'";
}
$andParts[]= "(" . implode($orParts, " OR ") . ")";
}
$and = implode ($andParts, " AND ");
echo $and;
this would produce the query part (Name like '%Big%' OR description like '%Big%') AND (Name like '%Dog%' or description like '%Dog%')
So, it will find any row, where dog and big are appearing in at least one of the columns name or description (could also be both in one column)
Since your original querystring is something like %big%dog%, so I assume you are okay with matching big wild dog. In this case, you can just use the AND operator.
(Name LIKE '%big%" and Name LIKE '%dog%")
myisam supports full text search:
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
One thing you could look into is Full Text Search for ms sql server.
https://msdn.microsoft.com/en-us/library/ms142571.aspx
it's similar to a "search engine" in that it works off of an algorithm to rank results and even similar words (think thesaurus type lookups)
It's not exactly trivial to set up, but it's easy enough to find a tutorial on the subject and how to query from FTS (as the syntax is different than say LIKE '%big%dog%')
Here's a sample query from the page linked above:
SELECT product_id
FROM products
WHERE CONTAINS(product_description, ”Snap Happy 100EZ” OR FORMSOF(THESAURUS,’Snap Happy’) OR ‘100EZ’)
AND product_cost < 200 ;
I have a MySQL table that looks like this:
index | tag | posts
-------------------------
1 | cats | 9,10
2 | a cat | 9,10
3 | kitty | 9,10
4 | meow | 9,10
I am trying to just return the row that matches a search query.
I passed the search parameter using a simple ?search=cats.
This is the PHP that I'm using:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print);
However the mysql_num_rows($query) prints 0 and the $print returns NULL. I can check it with ($print == ""), it evaluates to TRUE and mysql_num_rows($query) returns 4.
I tried setting the search query to something that wasn't in the table and it retuned FALSE as expected. I also tried removing the WHERE tag = '$search' and it returns the table like it should.
Is there something I'm overlooking?
Edit
Took everyone's advice and the code I'm using now is:
$search = mysql_real_escape_string($_GET['search']);
var_dump($search); //prints string(4) "cats" just like it should
$queryText = "SELECT * FROM tags WHERE tag = '%".$search."%'";
echo($queryText); //SELECT * FROM tags WHERE tag = '%cats%'
$query = mysql_query($queryText) or die(mysql_error()); //no error
$rows = mysql_num_rows($query); //this returns 0 and I know it should match 1 row
echo('rows: '.$rows);
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print); //empty
Still have the same problem. The mysql_query is retuning NULL instead of the row or FALSE if it doesn't match.
(in the future I will use the mysqli API, but I would like to finnish this project in mysql. thanks for your suggestions and advice)
Try this code now.
Remeber when you want to debug something in PHP the faster way is var_dump not echo. Also you should avoid mysql_api because they are deprecated, use PDO instead PDO on PHP.net
var_dump($_GET); // Just for debuggin if as something
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'");
// echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
var_dump($result);
//$print = $result['posts'];
//echo($print);
Ok so after referring to the above edit you made, here is the solution
Use "LIKE" instead of "=" when using wildcard "%"
So your query now should be
$queryText = "SELECT * FROM tags WHERE tag LIKE '%" . $search . "%'";
[I created the exact same db on my local system and ran the same code you gave, After making the above changes, It runs as expected]
$search = $_GET['search'];
echo $select_query="SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'";
$query = mysql_query($select_query);
echo(mysql_num_rows($query));
while($result = mysql_fetch_array($query))
{
print_r($result);
}
Note:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
That is very dangerouse: It allow sql incersion code to your database. You must always escape all what you get from the client.
$search = mysql_real_escape_string($_GET['search']); //It require open database connection.
Note2:
mysql_query is obsolete, use mysqli instead ;-)
Answer:
If you have not answer, you probable has an error in an other part.
Try
//1) Look if your search has a correct value
var_dump($search);
//2) Replace the query with (just for debugging):
$query = mysql_query("SELECT * FROM tags WHERE tag = 'cats';");
You may also use "tag like '%cats%'" if you want a more flexible search.
If you remove the WHERE tage = '$search', it cannot return the table like it should because your mysql_fetch_array is not in a while loop... but that aside...
// make sure before you execute the code to check that $_GET['search'] is not empty
// start with escaping the search-value (for mysql-injection)
$search = msyql_real_escape_string($_GET['search']);
// changed the query so it searches for tags containing the search value.
// if you would have records with tags "blue cat" and "red cat" it shows them both
// when searching for "cat"
$query = mysql_query("SELECT * FROM tags WHERE tag LIKE '%".$search."%'");
// put the number of rows in a var
$num = mysql_num_rows($query);
// check this var if it's not 0
if ($num != '0'){
while ($row = mysql_fetch_array($query){
echo $row['posts'];
// etc...
}
} else {
// 0 rows found
echo "nothing found";
}
I've created an ajax search box using the keyup function to find profiles in my database.
$('#asearch').keyup(function(){
var search_term = $(this).val();
The problem I'm having is that in my search box once I hit the space bar after typing the first name my page is no longer populated with results. Looking to make it so I can search a first name enter a space and a last name and still have results.
if (isset($_POST['search_term'])){
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if (!empty($search_term)){
$search = mysql_query("SELECT `firstname`, `lastname` FROM `tempusers`
WHERE `firstname` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
while ($results_row = mysql_fetch_assoc($search)) {
echo '<li>', $results_row['firstname'],' ', $results_row['lastname'], '</li></br>';
}
}
}
Tried using a regex $search_term = preg_split('/[\s]+/', $search_term); but it did not work like I was hoping it would. Any tips one may have will be greatly appreciated
Use the trim() function:
Strip whitespace (or other characters) from the beginning and end of a
string.
Plugging it into your code:
$search_term = mysql_real_escape_string(htmlentities(trim($_POST['search_term'])));
By the way, is there a reason that you are using htmlentities on input?
Like Blam said before sometimes is needed to split search string.
I am often using this kind of approach:
$search_term = str_replace(' ','%', trim($search_term));
//"paul dyk" will be changed to "paul%dyk"
//% will match any charackers between those you need. So if you need filter out those names like "pauladyk juk" use $search_term = str_replace(' ',' % ', trim($search_term)); as then spaces must exist, but there can be any words between them.
$search = mysql_query("SELECT CONCAT_WS(' ',firstname, lastname) as full_name FROM tempusers WHERE CONCAT_WS(' ',firstname, lastname) LIKE '%".mysql_real_escape_string($search_term)."%'");
//I would use concat_ws to join strings so if one of them is NULL it will not matter. Using concate with NULL you get no result
while ($results_row = mysql_fetch_assoc($search)) {
echo '< li>' . $results_row['full_name']. '</ li>< br>';
}
Let's start with a "side comment":
You are just looking into the firstname column in your select query. One way to find "firstname lastname" might be to modify your search:
$search = mysql_query("SELECT firstname, lastname FROM tempusers
WHERE CONCAT(firstname, ' ', lastname) LIKE '%$search_term%'");
So if you want to find anything in the lastname you need to look there, too.
Then back to the search query:
What I usually do first is split the query into "tokens". I do that to make sure that I can also find - for example "lastname firstname" and similar queries (for example people might enter "paul dyk" and still want to find "paul van dyk").
A simple way of doing so is by using explode(' ', $search_term), which will work as long as your users behave. Another option would be the regex you mentioned in your question.
Then use these "subqueries" to search your database.
explode() will give you an array of words.
array(
'paul',
'van',
'dyk'
)
From there you need to build your SQL query:
// DON'T DO THE ESCAPE THING BEFORE THIS!
$words = explode(' ', $search_term)
$sql = 'SELECT `firstname`, `lastname` FROM `tempusers` WHERE 1 = 1';
for ($words as $word) {
if (!empty($word)) {
$word = mysql_real_escape_string($word);
$sql .= " AND (firstname LIKE '%" . $word . "%' OR lastname LIKE '%" . $word . "%')";
}
}
$search = mysql_query($sql);
That will build a query where it will search for each word "one by one" and not in a specific order. It's a bit slower, though.
$('#asearch').keyup(function(){
var search_term = this.value.trim();
});
or if insisiting on jQuery
$('#asearch').keyup(function(){
var search_term = $.trim($(this).val());
});
will trim away whitespace at the end/beginning before the value is sent serverside.
i have a variable and an user_name i want to search on a string(function_description) of the user_name for it
whats wrong with this :
$function_keywords = mysql_real_escape_string($_POST['function_keywords']);
if($function_keywords=="" || empty($function_keywords)){
redirect("show.php?functions=PHP");
}
//trim whitespace from the stored variable
$trimmed = trim($function_keywords);
//separate key-phrases into keywords
$trimmed_keywords = explode(" ",$trimmed);
// Build SQL Query for each keyword entered
foreach ($trimmed_keywords as $trimm){
// MySQL "MATCH" is used for full-text searching.
//this code is ebv weird , should check out soon!
$query = "SELECT *
FROM functions
WHERE isEnabled=1 AND isPrivate=0
AND function_description LIKE '{$trimm}'
AND user_name='{$user_name}'
";
// Execute the query to get number of rows that contain search kewords
$results=mysql_query ($query,$connection);
as far as "like" syntax goes you have to use the '%' symbol. if you query for
select * from table where column like '%yourkeyword%'
then it returns any rows with 'yourkeyword' inside the table column.
your statement will be true only if the column = 'yourkeyword'
That's highly inefficient. If someone puts in 5 keywords, you'd be running the search 5 times and getting 5 sets of results. Try something more along these lines:
$words = $_POST['function_keywords'];
if ($words == '') {
... abort ...
}
$parts = trim(explode(' ', $words));
$clauses = array();
foreach($parts as $part) {
$clauses[] = "function_description LIKE '%" . mysql_real_escape_string($part) . "%'";
}
$clause = implode(' OR ' , $clauses);
$sql = "SELECT .... WHERE (isEnabled=1) AND (isPrivate=1) AND (user_name='$user_name') AND ($clause)";
$result = mysql_query($sql) or die(mysql_error());
This'll build up a long series of or statements for each keyword specified, and run the whole thing as a single query.
To see if the function_description contains the keyword you need to use '%' which stands for anything much the way '*' does in unix. Try function_description LIKE '%{$trimm}%'