1

I'm doing a little ajax question-result system. When user types something into the textarea, the result is automatically searched and outputted.

Problem is that every time user types the question that contains "" or '' - the search is unsuccessful. Is there any way I can add backslash to "" or '' inside the string, so it'd be ignored?

Or is there any filter that ignores the "" or ''?

I need the question to be searched with quotes, because questions in database contains them.

Here's the code:

$q = $_POST['q'];
// for every " or ' in $q add \ before it
$results = array();
$result = array();
$count = 0;
$stmt = $dbh->prepare("SELECT result FROM quest WHERE quest LIKE '".$q."%'");
if($stmt->execute()){
    $result = $stmt->fetchAll(PDO::FETCH_OBJ);
    $count= $stmt->rowCount();
}
if($result != NULL){
    foreach($result as $part){
        foreach($part as $item){
            $results[] = $item;
        }
    }
    echo htmlentities($results[0], ENT_QUOTES, "UTF-8");
}
Dawid Zbiński
  • 5,521
  • 8
  • 43
  • 70
  • you need to use a prepared statement, that's why. MySQL is complaining about that, but you're not giving it the chance ;-) – Funk Forty Niner Apr 25 '16 at 17:51
  • I don't agree that this is a duplicate @Fred -ii-. I know that your intentions are the best, but maybe someone wouldn't realize that it is almost the same thing as SQL Injection (as I did) and would search for this kind of question :) – Dawid Zbiński Apr 25 '16 at 18:02
  • *"Now I see. Thanks for help. I'll mark as correct in 6mins. – Dawid Zbiński 5 mins ago"* - and the duplicate is about what, bringing in monkeys from the rain forest? what do you call this http://php.net/manual/en/pdo.prepared-statements.php from the answer you accepted? and http://stackoverflow.com/a/60496/ from the dupe. – Funk Forty Niner Apr 25 '16 at 18:04
  • therefore, you shouldn't have accepted that answer. – Funk Forty Niner Apr 25 '16 at 18:07
  • I found your reply quiet offensive, but ok. You're the boss here. You might be right. – Dawid Zbiński Apr 25 '16 at 18:13
  • Offensive?! you're kidding me right? *I'll just slap myself here, lol* – Funk Forty Niner Apr 25 '16 at 18:14

2 Answers2

0

Try using addslashes() Function

Harish Kumar
  • 133
  • 6
0

You are not using prepared statements correctly, and that's why you are having this issue. If you use prepared statements correctly, they solve this issue for you. The docs for this are actually pretty good.

http://php.net/manual/en/pdo.prepared-statements.php

EDIT: Please take the time to learn how to use them correctly. If not, your code is susceptible to SQL injection.

TylerN
  • 60
  • 5