In this article, I will tell you how to deal with the apostrophe not working in form data that writes to MySql using PHP.
I do a lot of work involving input forms on PHP pages that write the input data to MySQL. Every time I do this, I have to account for the user who puts in an apostrophe. In most cases, it is intended.
This morning I was writing a form that allows users to enter movies. What was one of the first movies that I tried to enter as a test? It’s Complicated. An appropriate title, no?
When you have not accounted for this apostrophe in your PHP file, you may receive a message that looks something like this:
Anyway, I run into this quite a bit and each time I find myself fishing through my old projects or the Internet for a solution. So, I write this solution as much for myself as for you
And, thankfully, despite all the ramblings you may find on the Internet, the solution is quite easy.
Let’s have a look. Assuming your variable is called $keyword, as mine is in the form I am working with right now, simply enter this after your $keyword variable:
$keyword = str_replace("'","''",$keyword);
Dealing with apostrophes when you are working with form data in a PHP file that writes to a database can be a headache. However, in the end, you just need that one line and you will be good to go.
Hope this helps. Cheers and Happy New Year, Richard