0

When I save "Ben and Jerry's" to my database, and later recall it from the database, into an input tag (so I can edit/resave it), I get

Ben & Jerry's

Where am I going wrong? (Notice that the "&" is correctly translated, but the apostraphe is not). Let me summarise what I am doing...

My web pages have

<meta charset="utf-8" />

and my server dispenses JSON data via PHP and

header('content-type: application/json; charset=utf-8');

My web form, using javascript/jquery, pre-post, pushes all form data thru

encodeURIComponent()

My PHP server code reads the data and pre-db-insert uses

filter_var() and FILTER_SANITIZE_STRING

My mysql db created with "utf8 - default collation" and my insert writes

Ben & Jerry&#39;s

Later.... I do a mysql select, and I thought I need only javascript call

decodeURIComponent()

to convert everything back to "Ben & Jerry's" but this appears not to be the case.

What am I missing?

  • You don't need to be encoding or decoding that unless you're using it in the URL. As long as you are sanitizing the string before it goes into your database you can just store the string `Ben & Jerry's` without worrying about the apostrophe. – Jack Jun 17 '16 at 15:22
  • The value has been HTML encoded. There's nothing specifically wrong with this, you just need to find out where that's happening in your code and remove it if it's not required. – Rory McCrossan Jun 17 '16 at 15:22
  • you need to figure out WHERE the uri encoding is occuring. if it's in the database like that, look at the insert code. if it comes OUT of the database with a `'`, then look at the output code. – Marc B Jun 17 '16 at 15:23
  • I convert my input to reduce/avoid injection - so perhaps my method is wrong. Should I use PHP html_entity_decode() after reading from the database? Am I createing more work than I need to? –  Jun 17 '16 at 15:25
  • 1
    Are you only converting quotes to prevent SQL injections? If so use parameterized queries. If you are encoding special chars to prevent XSS injections that `&` should also have been encoded. Maybe add your code for `inserting` and `selecting` – chris85 Jun 17 '16 at 15:32

1 Answers1

0

Based on the comments above, and the two links below, I went with prepared statements. I had avoided such until now because of inexperience - I write old school procedure code and most examples given on the php.net page have moved from that style. I hope something here and above helps others...

What is parameterized Query?

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

Thanks everyone

Community
  • 1
  • 1
  • 1
    `pdo` and `mysqli` are both options that support parameterized queries. The `mysqli` has the procedural style still. – chris85 Jun 17 '16 at 20:23