Search code examples
phpescapinghtml-escape-characters

PHP Printing a string with multiple single quotes


So I'm having an issue that seems like it should be a pretty simple fix but I can't seem to figure it out.

I'm using prepared statements to query data from my SQL and the return is correct. I have var_dumped the result and confirmed the the information is there.

The table shows this: 2 'all of the way'

The array variable shows this: 2 \'all of the way\'

But when I echo it to the page, I see this: 2

I have tried htmlspecialchars, htmlentities, addslashes, stripslashes and a few combinations of those. Is there a function I'm missing here? Google isn't really helpful because the words to describe the problem are pretty generic.

Thanks in advance!

EDIT Sorry - didn't add my code because I assumed it was a function I wasn't familiar with. Here it is.

        $Res = $db -> query("SELECT * FROM 01_02_item WHERE ParID = $ParID AND active = 1 ORDER BY OrderID") -> fetchAll(PDO::FETCH_ASSOC);
        if(empty($Res[0])) $return = "<span class = 'nodata'>No data</span>";
        foreach($Res as $r){
            $id = $r['id'];
            $name = htmlspecialchars($r['Name']);
            $title = stripslashes(htmlspecialchars($r['Description']));
            $return .= "<li href = '$id' title = '$title' name = '$name'>$name</li>";
        }
        return $return;

Solution

  • By default htmlspecialchars() doesn't escape single quotes.

    You should use htmlspecialchars('foobar', ENT_QUOTES).