0

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.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
rabib galib
  • 27
  • 1
  • 1
  • 7
  • 7
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jul 20 '17 at 12:35
  • try `$str = preg_replace("/[\s]/", "%", $str)` and put this in `$str` in query rather than putting query in loop. – Dileep Kumar Jul 20 '17 at 12:43

1 Answers1

0

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']));
    }
tylermoseley
  • 122
  • 5
  • can u help me out with https://stackoverflow.com/questions/45320798/search-with-split-text-in-db-and-get-re-hitting-value this prob too. It's my another quest. – rabib galib Jul 26 '17 at 10:17