Split out a string and search'em in sql - php

I'd like to split a string into array and search every split array in query that'll pull related answer from database.
Here is my code. But it's not working....
$str=$_POST['search'];
$a=preg_split("/[\s]/", $str,);
foreach ($a as $search) {
$sql = "SELECT answer FROM query_tbl WHERE (q1 like \"$search%\" OR q2 LIKE
\"$search%\" OR q3 LIKE \"$search%\" OR q4 LIKE \"$search%\")";
$record = mysqli_query($link, $sql);
$rows=mysqli_fetch_assoc($record);
echo json_encode(array('ans'=>$rows['answer']));
}
Imagine 1$str=" this makes no sense ";1 then the query will be searched by "this", "makes", "no", "sense". If the sub-string matched with answer lies in query then it'll be printed.

There are a couple of issues here. (I am assuming this is PHP)
First, I would use this syntax for your string concatenation:
"SELECT answer FROM query_tbl WHERE (q1 like '".$search."%'.OR..."
Secondly, check out the implode function fro the "OR"s and use the loop to just add the dynamic part to the static string http://php.net/manual/en/function.implode.php :
$str=$_POST['search'];
$a=preg_split("/[\s]/", $str);
var_dump($a);
foreach($a as $key => $word) {
$a[$key] = "q1 like '".$word."%'";
}
$ORS = implode(" OR ", $a);
$sql = "SELECT answer FROM query_tbl WHERE ".$ORS.";";
$record = mysqli_query($link, $sql);
$rows=mysqli_fetch_assoc($record);
echo json_encode(array('ans'=>$rows['answer']));
}

Related

How to iterate through database results, compare each value to that in an array and return the matching id?

I am trying to build a function that will be given an array. and from this array, iterate through an entire table in the database trying to find a match. If it does find a match. I would like it to echo out the ID of that match from the database table.
If possible I would also like it to say if it found any close matches?
What's making this tricky for me is that it needs to match all values despite their order.
for example, if the function is given this array:
$array = array(1,2,3,4,5)`
and finds this array in the database:
$array = array(2,3,5,1,4)
it should consider this a match
Also, if it finds
array(1,2,3,4,5,6)
It should output this this as a match except for value 6.
Let me refrase your question, is this correct?
Based on an array of ID's, return all records whose ID's are in the array.
If so, use the IN operator:
SELECT *
FROM tableName
WHERE columnName IN (value1, value2, value3, etc.)
So first we need to transform the given array into a comma-seperated list:
$comma_seperated = implode(', ', $array);
Now we have a comma-seperated list we can use in our query:
$comma_seperated = implode(', ', $array);
$query = "SELECT *
FROM tableName
WHERE id IN (" . $comma_seperated . ")";
// execute query, don't use mysql_* functions, etc. ;)
You could use any of the options:
option 1:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM youtable WHERE id IN(".implode(",",$array).")";
option 2:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM yourtable";//Select ids
Now iterate through query results, say results are stored in $query_results,
$result=array();
foreach($query_results as $row){
if(in_array($row['id'],$array)){
$result[] = $row['id'];
}
}
You can use array difference to get the result just run the code and you will understand
Case 1
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array1, $array2);
print_r($result);
Case 2
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array2, $array1);
print_r($result);
And after that you can the count of $result and put it in your logic.
Case 1:
Maybe you can select the unique values from the database.
SELECT DISTINCT unique_values_that_need_for_compare_column FROM table
This SQL result will be the $databaseValues variable value.
Than iterate through the array that the function gets.
foreach ($functionArray as $value) {
if (in_array($value, $databaseValues)) {
// you have a match
echo $value;
}
}
Case 2:
Or you can make a query for every value:
foreach ($functionArray as $value) {
$query = "SELECT COUNT(*) as match FROM table WHERE unique_values_that_need_for_compare_column = " . intval($value);
// fetch the result into the $queryResult variable and than check
if ($queryResult['match']) {
// you have a match
echo $value;
}
}

How to order this array to High to Low? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to sort the results of this code?
I have made this code which allows a user to type in a search bar a question. This code then takes that question and looks for watching words with questions in my database. It then counts the number of matching words for each question. Once done it then displays the top 4 best matched questions depending on how many words match.
However at the moment it displays these matches from lowest word match to highest word match (low-to-high) and I was it the other way around so that it displays the best match first (high-to-low). How do I do this in this code?
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
if ($matchingwords >= 4){
?>
<li><a href='<?php echo $row['url']; ?>'><?php echo $title ?><i> No. matching words: <?php echo $matchingwords; ?></i></a></li>
<?php
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
If you have saved you data in an array you can simply reverse it by using http://www.php.net/manual/en/function.array-reverse.php
Otherwise there are some sort functions
http://php.net/manual/en/function.sort.php
I think you have problem in sorting an array.
If you have an array, sorting is not a matter.
Having different types of sorting found in php.
arsort()
Sort an array in reverse order and maintain index association
http://www.php.net/manual/en/function.asort.php
You can use this array function or let me know your questions briefly.
you can write a own filter function
// sorts an array by direction
function arr_sort($arr, $index, $direction='asc')
{
$i_tab = array();
foreach ($arr as $key => $ele)
{
$i_tab[$key] = $arr[$key][$index];
}
$sort = 'asort';
if (strtolower($direction) == 'desc')
{
$sort = 'arsort';
}
$sort($i_tab);
$n_ar = array();
foreach ($i_tab as $key => $ele)
{
array_push($n_ar, $arr[$key]);
}
return($n_ar);
}
for example you have an array $arr = array('key' => 'value', 'key2' => 'value');
you can now sort by key2 asc with
$arr = arr_sort($old_arr, 'key2', 'desc');
so you can put the total count of matching words into your array as a node for any entry and filter it by it descending
note this requires Mysql version 4+
A fulltext sql query returns values based on relevance.
Example:
SELECT *, MATCH (title)
AGAINST ('$search_term' IN NATURAL LANGUAGE MODE) AS score
FROM posts;
This is how you would implement it
$q = "SELECT *,MATCH (title) AGAINST ('$search_term' IN BOOLEAN MODE) AS relevancy FROM
posts WHERE MATCH (title) AGAINST ('$search_term' IN BOOLEAN MODE) ORDER BY
relevancy DESC";
This will return the posts in order by relevancy. May need to remove the '' around $search_term but you can figure that out with testing.
Please read up on Fulltext sql queries and the match() function. It is all clearly documented.

PHP compare two arrays from different locations

I am wanting to compare two different arrays. Basically I have a database with phrases in and on my website I have a search function where the user types in a phrase.
When they click search I have a PHP page which 'explodes' the string typed in by the user and its put into an array.
Then I pull all the phrases from my database where I have also used the 'explode' function and split all the words into an array.
I now want to compare all the arrays to find close matches with 3 or more words matching each phrase.
How do I do this?
Well what I've tried totally failed, but here is what I have
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //user entered data
$search_term = str_replace ("?", "", $search_term); //removes question marks
$array = explode(" ", $search_term); //breaks apart user entered data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array) . " LIMIT 0,10";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title'];
$thetitle = str_replace ("?", "", $thetitle);
$title_array[] = $thetitle;
$newarray = explode(" ", $search_term);
foreach ($newarray as $key=>$newword) {
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value);
$contacts = array_diff_key($thenewarray, array_flip($newarray));
foreach($contacts as $key => $value) {
echo $newword."<br />";
echo $value."<br /><hr />";
}
}
}
But basically all I want is to display suggested phrases which are similar to what the user has already typed into the search box.
So If I searched "How do I compare two arrays that have the same values?", I would see 10 suggestions that are worded similar, so like "How to compare multiple arrays?" or "can I compare two arrays" etc...
So basically like when I first posted this question on this site, I got other questions that may help, thats basically what I want. This code im using was origionally to match just one word or an exact matching string, im editing it to find matching words and only show phrases with 3 or more matching words.
I don't think that this is the best solution for your search script. But I'll try to give you the answer:
<?php
$string1 = "This is my first string";
$string2 = "And here is my second string";
$array1 = explode(" ", $string1);
$array2 = explode(" ", $string2);
$num = 0;
foreach($array1 as $arr) {
if(in_array($arr, $array2))
$num++;
}
$match = $num >= 3 ? true : false;
?>
use array_intersect function
$firstArray = "This is a test only";
$secondArray = "This is test";
$array1 = explode(" ", $firstArray);
$array2 = explode(" ", $secondArray);
$result = array_intersect($array1, $array2);
$noOfWordMatch = count($result);
$check = $noOfWordMatch >= 3 ? true : false; ;

Picking numbers in an order

I had a task to slide images from a mysql database using jquery slide and not the animation scripts. The slide is supposed to show at least the most recent ten images that was uploaded. With that I first of all wrote a random query
mysql_query("select * from tblname order by rand() limit 1);
But as expected, it picks the images at random irrespective of when it was posted and of course it wasn't the most recent ten. After some thought I now had to first run a query to get the most recent ten
mysql_query("select * from tblname order by ID limit 10);
while($row=mysql_fetch_array($sql){
$slideid=$slideid.",".$row['recordid'];
}
this of course results to a variable of this order
$var="23,22,24,34,27,78,56,87,98,55";
I tried handling it like an array but it wasn't giving any positive result, hence I had an issue of how to pick this numbers and use it for the slide
$myArr=explode(',',$var);
sort($myArr);
for($i=0;$i<count($myArr);$i++)
{
echo $myArr[$i];
}
Edit: For better efficiency use:
$myArr=explode(',',$var);
sort($myArr);
foreach ($myArr as $val)
{
echo $val;
// Or do whatever else you want with each one.
}
Edit 2: See comments below on efficiency vs for loops vs unexpected results. :)
Based on your comments I will offer my 2p into the mix
this is what I did $slideid="23,22,24,34,27,78,56,87,98,55"; $arr =
explode(',',$slideid); foreach ($arr as $val) { //lets get the
variables from the form post $rs = mysql_query("SELECT * FROM tblname
WHERE id='$val'") or die(mysql_error());
while($row=mysql_fetch_array($rs)){ echo "<img src='image/$image'>"; }
} the images are displayed one by one using jquery slide
Now I think we are wasting time dealing with exploding this variable because mysql has the nifty IN() function (possibly in other db's I don't know)
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid})") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}
I hope this helps
$var="23,22,24,34,27,78,56,87,98,55";
$arr = explode(',',$var);
foreach ($arr as $val) {
// work with $val
}
explode splits the string to an array
1) Explode the string into an array, splitting on the comma.
2) You didn't say whether you wanted to re-order the numbers into numerical order, or process them in the order they're already in. If the former, sort the array with sort($arr);
3) Loop over the array in sequence and do something with each number
$str = '1,2,3,4,5,6';
$arr = explode(',', $str);
foreach($arr as $num) echo $num.'<br />';
Note if there is any change of spaces after commas, a better choice would be preg_split rather than explode, as this is more dynamic.
$arr = preg_split('/, ?/', $str);
You can achieve this using php explode function
$pieces = explode(",", $var);
echo $pieces[0]; // piece1
echo $pieces1; // piece2
.
.
.
echo $pieces[n]; // piece n
I think you need to get result of order with respect to order of variable here
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid}) ORDER BY FIELD(id, {$slideid}) ") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}

Explode a String and Check Database for Duplicate

How can I take a string business, jquery, css and explode that string and check a mySQL database to see if each one of the single words is already inside a database entry?
Thanks,
Drummer392
$string = "business, jquery, css";
$exploded = explode(",", $string);
$result = /* database select query */
foreach ($exploded as $value) {
// $value contains the value being processed
// compare $result to $value and do what's needed
}
PHP Manual: explode()
Hope that give you an idea as to what you need to do.
Edit: thanks to Chris for the suggestion of doing the database query first
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $conn);
$string = "business, query, css";
$array = explode(", ", $string);
foreach($array as $str){
$result = mysql_query("SELECT * FROM tableName WHERE columnName='$str'", $conn);
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
//found
else
//not found
}
Use PHP's explode function with a ", " delimiter, assigning to a new array variable.
I would improve upon the previous answer, I feel it would be better to use the SELECT query outside of the foreach loop. Then you'll avoid executing the same query 3 times.
$result = /* database select query */
foreach ($exploded as $value) {
// compare $result to $value and do what's needed
}

Categories