-1

I am escaping data prior to DB insertion using: $entry = mysqli_real_escape_string($link, $value); and then using htmlspecialchars() on the output before displaying, however in my output I appear to have slashes within the string, as in It\'s not working. Obviously I don't want that.

Code (abbreviated for simplicity):

function insertData($post)
    $dbc = mysqli_connect(DB_HOST, DB_UN, DB_PW, DB_NAME);
    foreach ($post as $key => $value) {
        $post[$key] = mysqli_real_escape_string($dbc, $value);
    }
    $insert = 'INSERT INTO products_test ('.array_keys($entry)[0].','.array_keys($entry)[1].') VALUES ("'.array_values($entry)[0].'","'.array_values($entry)[1].'")';

    if (mysqli_query($dbc, $insert)) {
        echo htmlspecialchars($post['name']).' has been added to the inventory';
    }

$post = [
    'name' => $_POST['name'],
    'narrative' => $_POST['narrative']
];

insertData($post);
Ryan
  • 767
  • 3
  • 9
  • 31

1 Answers1

1

echo stripslashes("It\'s not working");

example: https://3v4l.org/tmqNP

manual: http://php.net/manual/en/function.stripslashes.php

That will get rid of the slashes from mysqli_real_escape_string, but instead of echoing the escaped string just echo the original one instead.

if (mysqli_query($dbc, $insert)) {
    echo htmlspecialchars($post['name']).' has been added to the inventory';
}

NOTE: OP changed code in question to reflect my answer after I posted it. I didn't just copy his code verbatim.

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • What do you mean by 'echo the original one instead'? Your code block mirrors what I'm already doing, doesn't it? – Ryan Jan 20 '16 at 01:29
  • ....yeah, after you edited the question and pasted my code... now that you've gone and changed the code the problem is that you are overwriting the $post variable with mysqli_real_escape_string'd version of it. mysqli_real_escape_string is escaping the quotes by adding that backslash. htmlentities isn't going to do anything, tht function is not relevant to this situation so just get rid of it. your options are 1) go back to using the original code you posted and create a new array instead of overwriting $post, then echo the $post array instead instead of the escaped one or use stripslashes. – I wrestled a bear once. Jan 20 '16 at 01:36
  • i meant htmlspecialchars not htmlentities – I wrestled a bear once. Jan 20 '16 at 01:42
  • So if I understand correctly, you're saying don't use the output from the database as the echo for the success message, just take the original input and echo that? – Ryan Jan 20 '16 at 01:53
  • if you're using the output from the database that's fine. but you're using the *input* *to* the database. all i'm saying is, don't echo stuff that you have run through `mysqli_real_escape-string`, but if you really really have to, use stripslashes. – I wrestled a bear once. Jan 20 '16 at 02:01