I'm building a category list and I'm unsure how to store the Ampersand symbol
in MySQL database. Is there any problem/disadvantage if I use '&'
. Are there any differences
from using it in a html format '&'
?

- 5,886
- 3
- 29
- 38

- 4,969
- 11
- 38
- 51
-
1Read this [link](http://stackoverflow.com/questions/3545735/storing-ampersand-in-database) – Mr. Alien Jul 28 '12 at 20:20
-
1Minor correction: the entity `&` should end in a semi-colon. – halfer Jul 28 '12 at 20:29
5 Answers
Using '&' saves a few bytes. It is not a special character for MySQL. You can easily produce the &
for output later with PHP's method htmlspecialchars()
. When your field is meant to keep simple information, you should use plain text only, as this is in general more flexible since you can generate different kinds of markup etc. later. Exception: the markup is produced by a user whose layout decisions you want to save with the text (as in rich-text input). If you have tags etc. in your input, you may want to use &
for consistency.

- 322
- 1
- 3
-
Is there any problem if I do this: $cat_name = 'Cars & Parts'; echo $cat_name; or it is mandatory to do it this way: $cat_name = htmlspecialchars($cat_name) ? Thank you for your answer. – inrob Jul 28 '12 at 20:49
-
It's not mandatory. `htmlspecialchars()` also takes care of quotes and `<` and `>` characters. If you output "Cars & Parts" in an html context, a browser would display an "&" for the `&`. Again, I would probably not store the `&` in the database. – Chris Jul 28 '12 at 21:09
-
Yep I decided this way. I'm going to store them as &. Thank you for your answer. Have a good day. – inrob Jul 28 '12 at 22:07
You should store it as &
only if the field in the DB contains HTML (like <span class="bold">some text</span> & more
). In which case you should be very careful about XSS.
If the field contains some general data (like an username, title... etc) you should only escape it when you put it in your HTML (using htmlentities for example).

- 7,493
- 1
- 32
- 39
Storing it as &
is an appropriate method. You can echo it or use it in statements as &
.
-
And when I echo out '&' would it appear as '&' or it should use some php function to translate it to the '&' symbol? – inrob Jul 28 '12 at 20:30
-
As a fellow learner of php, I suggest you just try it. It honestly is the best way to learn. – ryno Jul 28 '12 at 20:43
-
1
-
yeah i tried it, it displays correct, I guess I'm going to use & as you and most of others suggested here :) Thanks for your answer. – inrob Jul 28 '12 at 20:46
We store '&' into database fields all the time, it's fine to do so (at-least I've never heard an argument otherwise).
If you're only ever using the string in a HTML page you could just store the HTML safe &
version I suppose. I would suggest that storing '&' and escaping it when you read it would be better though (in-case you need to use the string in a non-HTML context in the future).