I’m building a web form to save user inputs into a MySQL database table and return the formatted results to the user as a web page. The following are stripped-down examples of the HTML and PHP files, showing insertion to just two columns of apostrophe_test, user (varchar) and comments (text):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
apptest.html
</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<form action="apptest.php" method="post">
Username: <input type="text" name="username" size="20" maxlength="20">
<br><br>
Comments: <textarea name="comments" rows="2" cols="30"></textarea>
<br><br>
<input type="submit" value="Submit"> <input type="reset" value="Reset">
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
apptest.php
</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<?php
$username = htmlentities($_POST['username']);
$comments = htmlentities($_POST['comments']);
$connection = mysqli_connect('localhost', '********', '********', '********')
or die('Error connecting to MySQL server.');
$query = "INSERT INTO apostrophe_test (username, comments) VALUES ('$username', '$comments')";
$result = mysqli_query($connection, $query)
or die('Error querying database.');
mysqli_close($connection);
echo 'Username: ' . $username . '<br><br>';
echo 'Comments: ' . $comments;
?>
</body>
</html>
The form works fine, storing inputs (with any double quotes, ampersands, etc. formatted as entities) into the database and returning the inputs as originally entered back to the user, EXCEPT…
If an input includes an apostrophe, such as a contraction like don’t, I immediately get a blank screen with “Error querying database” and nothing is added to the database. If I “escape” the apostrophe/single quote by typing don\'t, the input is accepted and appears in the database as don’t (without the backslash) but appears in the return web page as don\'t (with the backslash).
Since the form is for public input, users need to be able to enter their comments in the accustomed manner (without any escape characters) and see a normal-looking return page. It’s fine if the database needs to use entities or whatever to store comments properly.
I realize this is a well-known issue and a Google search displays many links with various remedies, but my current knowledge is not up to the task of understanding everytlhing that’s being suggested. What would be a straightforward, effective way to modify the above code so regular apostrophes (the lower case key next to Enter) will be accommodated by MySQL? Thanks!