Search code examples
phptrimstriphtmlspecialcharsapostrophe

Apostrophe cause problems inserting query when using trim, stripslashes and htmlspecialchars


When I use text with an apostrophe, the query don't work.

Example: This is Ben's party.

This is the function I use:

function text_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

This is the html:

<textarea name="text" rows="20" cols="89"></textarea>

The php script:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["text"])) {
    $errors[] = "There is no text";
} else {
    $text = text_input(mysqli_real_escape_string($con, $_POST['text']));
}

if(empty($errors) === true){
    mysqli_query($con, "INSERT INTO texts (text) VALUES ('$text')");
    exit();
}

Solution

  • You need to do the mysqli_real_escape_string after all the other stuff. Otherwise stripslashes will remove the slashes you just added with the escape.

    So:

    $text = mysqli_real_escape_string($con, text_input($_POST['text']));