Question

The code below takes a string protects its using mysqli_real_escape_string. but not geting expected output working fine without the mysqli_real_escape_string but need that for protection.

  $str = mysqli_real_escape_string($con,$_POST['str']);
    /*
      get each word in the sentence using for-loop then 
    */
    switch($eachword){
        case ':)': $eachword = '<img src="smile.gif">';
        break; 
    /*
      and so forth and so on
    */
    }


    $newstr .= $eachword;
    //for-loop ends


**mysqli_query($con,"insert into tbl(comment)VALUES($newstr)");**

e.g

  • input : $str = "here i am :) fine";

  • expected output : $newstr="here i am <img src="smile.gif"> fine";

  • curernt output : $newstr="here i am :) fine";

UPDATE

NOW everything works fine. Thanks to supporters.

Was it helpful?

Solution 2

UPDATED

Note that you must be already connected to a database, for mysqli_real_escape_string to work, because it takes into consideration, the default character set of your selected database. Are you connecting to a database before using it?

And in your question, I don't even see a query. There will be no advantage in using mysqli_real_escape_string unless you're going to insert the passed string into a database.

Now I see that you're replacing smileys with tag, then you're inserting it into a database. However, if I were you, I would do the following :

function ParseSmiley($str)
{
    $smileys = array(
        ':)' => "<img src='smile.gif' />" //Put all your smileys in this array
    );

    $parsed_string = strtr($str, $smileys);
    return $parsed_string;
}

When you're inserting your content into database, do not convert it into tags. Instead, when you display it, use the function ParseSmiley()

$parsed_string = mysqli_real_escape_string($con,$_POST['str']);

mysqli_query($con,"INSERT INTO tbl (comment) VALUES ($parsed_string)");    

Then when you want to display the content, let's say the string is in $content, display it like this :

echo ParseSmiley($content);

OTHER TIPS

You are running mysqli_real_escape_string over some data immediately before … not using at all in your code sample. So it doesn't make any sense.

Use mysqli_real_escape_string immediately before inserting the variable into a string of SQL and nowhere else. (Better yet, use prepared queries and bound arguments).

If you are trying to defend against XSS, then use htmlspecialchars immediately before inserting a variable into a string of HTML.

Don't use either before comparing user input to some text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top