I have a query from user to search in mysql database
<input type="text" name="query_textbox"><input type="submit" name="search_button">
<?php
if (isset($_GET['search_button']))
{
$query = $_GET['query_textbox'];
$command = "SELECT * FROM `table` WHERE `ProteinName` LIKE '%$query%';";
$result = mysql_query($command);
echo $result;
}
?>
When I put 'human' in textbox then it works. But when I search for 'human protein' it shows 0 results.
Now the question is "if I search for a query including whitespaces like 'human protein', it should show me result for 'human protein' as well as for 'human' and for 'protein'. How to do that?
You could do something like this:
$query = $_GET['query_textbox'];
// explode the query by space (ie "human protein" => "human" + "protein")
$keywords = preg_split("#\s+#", $query, -1, PREG_SPLIT_NO_EMPTY);
// combine the keywords into a string (ie "human" + "protein" => "'%human%' OR '%protein%'")
$condition = "'%" . implode("%' OR '%", $keywords) . "%'";
$command = "SELECT * FROM `table` WHERE `ProteinName` LIKE $condition;";
$query = $_GET['query_textbox'];
// explode the query by space (ie "human protein" => "human" + "protein")
$keywords = explode(" ", $query);
foreach($keywords as $key => $value){
$condition[] = `ProteinName` LIKE "'%".$value."%'"
}
$cond_str = implode(' OR ', $condition);
$command = "SELECT * FROM `table` WHERE $cond_str;";
Related
I have a databse table with 100K rows and an array of 100 items. And I need to find if an array item is found in my Users table username row.
My database table Users
| id | username | fullname |
1 John John Smith
2 Elliot Jim Elliot
3 Max Max Richard
My array looks like this
[
{
string: 'Hello, this is Elliot from downtown Las Vegas!'
},
{
string: 'Hey how are you?'
}
]
My idea was to do a foreach loop through every row in my Users table (100k records) and find if it matches in my array, but it is so slow.
foreach ($MyArray as $Array) {
foreach ($dbrows as $dbrow) {
if (strpos($Array['string'], $dbrow['username']) !== false) {
echo 'found it!';
break;
}
}
}
It will be a bit hit and miss as you may find users with all sorts of weird names that match normal words, this approach splits the input into words and then uses them to form an in clause to search the database. So it only looks at records that match rather than all records...
$search = 'Hello, this is Elliot from downtown Las a1 Vegas!';
$words = str_word_count($search, 1);
$bind = str_repeat("?,", count($words));
$bind = trim($bind, ",");
$query = $conn->prepare("select * from users where username in ($bind)" );
$types = str_repeat("s", count($words));
$query->bind_param($types, ...$words);
$query->execute();
$res = $query->get_result();
while($row = $res->fetch_assoc()) {
// Process result
}
It also uses prepared statements, which is where all of the $bind and $types processing comes in. If you look at $query you will see how it's built up.
I think the better way was to separate your search arrays into words, and use it in the query, like:
<?php
// Assuming your search array is $search...
$words = array ();
foreach ( $search as $text)
{
$words = array_merge ( $words, explode ( " ", trim ( preg_replace ( "/[^0-9a-z]+/i", " ", $text))));
}
$words = array_unique ( $words);
$in = "";
foreach ( $words as $text)
{
$in .= ",'" . $mysqli->real_escape_string ( $text) . "'";
}
if ( ! $result = $mysqli->query ( "SELECT * FROM `Users` WHERE `username` IN (" . substr ( $in, 1) . ")"))
{
echo "MySQL error!";
}
// Results at $result
?>
You can use regular expressions:
<?php
$query_string = "bla bla bla...";
$qry = $mysqli_query($conn, "SELECT *FROM table WHERE username REGEXP '$query_string'");
?>
Regular expression matches data individually from table.
Ok so when a user types their search phrase in the search input, I would like it to match the exact phrase or the key words entered.
I.e
So the title of a post is "Search the Database"
$searchVal = "Search database";
WHERE post_title LIKE '%" . $searchVal . "%'
The above code doesn't find a match as the title has "the" between Search Database.
How could I get it to match.
I thought maybe using explode but Im getting an error:
$sVals = explode(" ", $searchVal);
foreach ($sVals as $s) {
$querySearchVals .= "OR post_title LIKE '%" . $s . "%'";
}
Hope that makes sense.
Cheers
Maybe this could help
$search_key = $_POST['searchkey']; //take the search text from the post method
$search_words = array();
$search_words = explode(" ",$search_key);
$q_string = "";
$last_index = intval(count($search_Words)) - 1;
for($i = 0; $i<count($search_Words);$i++)
{
$q_string = $q_string . " post_title LIKE '%$search_words[$i]%' ";
if($i != $last_index)
$q_string = $q_string . " OR ";
}
And to make it even more accurate, you may skip the articles like A, The, An etc
You may want to insert the % in between the words and execute with 1 where clause. some thing like below should work.
$searchVal = "Search database";
$querySearchVals = "post_title LIKE '%";
$sVals = explode(" ", $searchVal);
foreach ($sVals as $s) {
$querySearchVals .= $s."%";
}
$querySearchVals .= "'";
echo $querySearchVals;
Hope it helps!
I am trying to build the logic to create a multi word LIKE statement for use with PDO.
This takes the search string $str to build the multiple parts of the LIKE section:
$str = $_POST['str'];
$keywords = preg_split('/[\s]+/', $str);
$totalKeywords = count($keywords);
$search = "%$str%";
$sql_str = " AND post_content LIKE :search0 ";
for($i=1 ; $i < $totalKeywords; $i++){
$search_bit = ":search" . $i;
$sql_str .= " AND post_content LIKE $search_bit ";
}
This is the SQL statement - with the $sql_str slotted into the correct point:
$sql = "SELECT d.ID
, d.post_date
, d.post_content
, d.post_cat_id
, d.post_label
, c.fld_cat
FROM tbl_log_days d
, tbl_log_cats c
WHERE d.post_cat_id = c.fld_id " . $sql_str . "
ORDER BY post_date";
Then for binding the variables, I have tried two approaches:
$stmt = $pdo->prepare($sql);
if (!empty($sql_str)) {
foreach ($keywords as $key => &$keyword){
$foo = '%'.$keyword.'%';
$stmt->bindParam(':search' . $key, $foo);
}
}
And also this (without the ampersand before the $keyword in the foreach line):
$stmt = $pdo->prepare($sql);
if (!empty($sql_str)) {
foreach ($keywords as $key => $keyword){
$foo = '%'.$keyword.'%';
$stmt->bindParam(':search' . $key, $foo);
}
}
However, when I search for e.g. "past hill" and check the resulting SQL that is actually run (I enabled query logging in MySQL), it only takes the last word in the search string:
SELECT d.ID
, d.post_date
, d.post_content
, d.post_cat_id
, d.post_label
, c.fld_cat
FROM tbl_log_days d
, tbl_log_cats c
WHERE d.post_cat_id = c.fld_id AND post_content LIKE '%past%' AND post_content LIKE '%past%'
ORDER BY post_date
I have done a var_dump of the $keyword variable when running a search and it returns:
string(4) "hill"
string(4) "past"
I can't work this one out. Is it possible to do what I'm trying to do?
I would do something like this
for($i=1 ; $i < $totalKeywords; $i++){
$search_num = "search" . $i;
$search_bit = ":" . $search_num;
$sql_str .= " AND post_content LIKE $search_bit ";
$foo = '%'.$keyword.'%';
$V[$search_bit] = $foo;
}
$query = $pdo->prepare($sql);
$query->execute($V);
(I haven't tested this code, so please excuse typos.)
I asked the same question on Sitepoint:
https://www.sitepoint.com/community/t/multi-word-like-prepared-statement-for-pdo-query/223738/5
And got a solution there:
$stmt = $pdo->prepare($sql);
if (!empty($sql_str)) {
for ($x = 0; $x<$totalKeywords; $x++) {
// add the percent signs, or make a new copy of the array first if you want to keep the parameters
$keywords[$x] = "%" . $keywords[$x] . "%";
$stmt->bindParam(':search' . $x, $keywords[$x]);
}
}
This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 6 months ago.
I have a string like this 'dubai,sharjah,' and I want to make it like this 'dubai','sharja',
I am passing the value dubai,sharjah, in the URL using ajax and my code
$city=$_GET['city'];
$sql = "SELECT * FROM filter where isdeleted = 0 ";
if ($city !="" && $city !="Empty" ){
$sql.=" and twon in ('".$citydata."')";
}
when I print the query, it's like this
SELECT * FROM filter where isdeleted = 0 and twon in ('dubai,sharjah,')
but I want it like this
SELECT * FROM filter where isdeleted = 0 and twon in ('dubai','sharja')
Can anyone guide me on how to do this using PHP?
Here's how I would approach it. I'm going to use PDO instead of mysqli because trying to get an array into mysqli_stmt::bind_param is just a pain.
First, create an array of cities, removing any empty values
$params = array_filter(explode(',', $city), function($c) {
return !empty($c) && $c !== 'Empty';
});
$paramCount = count($params);
$query = 'SELECT * FROM filter where isdeleted = 0';
Now generate a placeholder string for your prepared statement.
if ($paramCount) {
$placeholders = implode(',', array_fill(0, $paramCount, '?');
// looks something like '?,?'
$query .= " AND twon IN ($placeholders)";
}
Now, prepare a statement
// assuming you have a PDO instance in $pdo created with something like
// $pdo = new PDO('mysql:host=localhost;dbname=your_db;charset=utf8', 'username', 'password', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare($query);
Execute and fetch values :)
$stmt->execute($params);
$filters = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cities = explode(",", $_GET['city']);
//escape!
foreach ($cities as $citykey => $city) {
$cities[$citykey] = "'" . mysql_real_escape_string($city) . "'";
}
$sql = "SELECT * FROM `filter` where `isdeleted` = 0";
if (!empty($cities)) {
$sql .= ' and `twon` in (' . implode(',', $cities) . ')';
}
An alternative is to use FIND_IN_SET(). No PHP code change needed.
$sql.=" and FIND_IN_SET(town, '".$citydata."')";
you can try to explode the string
$cityparts = explode(",",$city);
and you can use
$cityparts[0] and $cityparts[1] in your query
array explode ( string $delimiter , string $string [, int $limit ] )
you can find more information on [http://www.php.net/explode]
hope this helps!!
You just have to explode and implode here. Rest is the problem with extra , in your string at the end.
$str = "dubai,sharjah,";
$citydata = implode("','",explode(',',rtrim($str,',')));
echo "'$citydata'";
test
After 6 answers I gotta add a 7th:
$sql.=" and twon in ('".str_replace(",","','",$citydata)."')";
You can do this.
$string = 'dubai,sharjah';
$cities = explode(',', $string);
echo $cities[0]; //dubai
echo $cities[1]; //sharjah
try this
$str = "dubai,sharjah,";
$arr = explode(",", $str);
$arr_temp = array()
foreach($arr as $s)
{
if($s!="")
{
$arr_temp[] = "'".$s."'";
}
}
$new_str = implode(",", $arr_temp);
echo $new_str; // output 'dubai','sharjah'
Now your Sql will be
$sql = "SELECT * FROM filter where isdeleted = 0 and twon in ($new_str) ";
You can use it
in $city I fix two values with, you can use here by $_GET ;
$city = "dubai,sharjah,";
$query_string ="";
$words = explode(",",$city);
for($i=0;$i<count($words);$i++){$query_string .= "'".$words[$i]."',";}
$query_string = substr($query_string,0,strlen($query_string)-4);
then use your query
SELECT * FROM filter where isdeleted = 0 and twon in ($query_string)
if ($city !="" && $city !="Empty" )
{
$city_exp = explode(',' $city);
$sql .= " and twon in ('".implode("', '", $city_exp)."')";
}
What we are basically doing here is putting the two values in an array by using explode and then separating each item in that array by using implode
DEMO
I have a search form that would like the users to search multiple terms. I'm currently using PHP PDO and I'm still learning... I was wondering if someone can tell me what I'm doing wrong here.
$varSearch = #$_GET['dms'];
$varTerm = explode(" ", $varSearch);
$termArray = array();
foreach($varTerm as $term){
$term = trim($term);
if(!empty($term)){
$termArray[] = "name LIKE '%".$term."%' OR tags LIKE '%".$term."%'";
}
}
$implode = implode(' OR ', $termArray);
$sql = $dbh->prepare("SELECT * FROM table WHERE ?");
$sql->execute(array($implode));
Have you considered doing something like this, instead:
$varSearch = #$_GET['dms'];
$varTerm = explode(" ", $varSearch);
$termsStringArray = array();
$termsArray = array();
foreach($varTerm as $term){
$term = trim($term);
if(!empty($term)) {
array_push($termsStringArray, "name LIKE ? OR tags LIKE ? ");
array_push($termsArray, $term);
array_push($termsArray, $term); // note, you can do this part differently, if you'd like
}
}
$implodedTermsString = implode('OR ', $termsStringArray);
$sql = $dbh->prepare("SELECT * FROM biz WHERE " . $implodedTermsString);
$sql->execute(array($termsArray));
Output:
// prepare statement
SELECT * FROM biz WHERE name LIKE ? OR tags LIKE ? OR name LIKE ? OR tags LIKE ? OR name LIKE ? OR tags LIKE ? OR name LIKE ? OR tags LIKE ?
// $termsArray (for execute)
Array
(
[0] => this
[1] => this
[2] => is
[3] => is
[4] => the
[5] => the
[6] => string
[7] => string
)
Basically, trying to separate the array data from the initial SQL query prepare string. Let me know if that works for you!
Though, you still will want to do some sort of checking (or sanitization,) of the data you are getting from the $_GET variable. That $_GET variable could have anything in it... and could be bad for SQL injections or other unwanted issues.
And, LIKE isn't necessarily going to be the most efficient way to do this type of database search. But if you use it (and I have used it for search things in the past,) try checking out: http://use-the-index-luke.com/sql/where-clause/searching-for-ranges/like-performance-tuning.
If anyone else needs this answer too...
$varSearch = #$_GET['dms'];
$varTerm = explode(" ", $varSearch);
$termArray = array();
foreach($varTerm as $term){
$term = trim($term);
if(!empty($term)){
$termArray[] = "name LIKE :term OR tags LIKE :term";
}
}
$implode = implode(' OR ', $termArray);
$sql = $dbh->prepare("SELECT * FROM table WHERE ".$implode."");
$sql->execute(array(":term"=>"%".$term."%"));
Remake
$my_explode = explode(" ",$search);
$query = array();
foreach($my_explode as $string)
{
$query[] ="name LIKE '%".$string."%' OR email LIKE '%".$string."%'";
}
$implode = implode(' OR ', $query);
foreach ($db->query("SELECT * FROM _table WHERE ".$implode."") as $info)
{
echo $info['name']."<br />";
}
Secure for injection, with php retrieve just alphanumeric chars
$search = preg_replace("/[^a-zA-Z0-9]+/", "-", $_GET["text"]);