How would I go about writing a SQL statement that would insert values that might contain an apostrophe (for example one person's last name was Conner and another's was O'Conner)? After some searching, I found examples using a double apostrophe (O''Conner example
) but each example had the string hard coded in the the INSERT
. I haven't run across any examples where the value may or may not contain an apostrophe.
My simple statement doesn't have any issues when no apostrophe is used but when one is it fails. I know I could replace the apostrophe using str_replace
but, obviously, that would cause the O'Conner example to be displayed as OConner.
Here is a shorthand version, just for an example:
page1.php
// PHP
include_once('phpdata.php');
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
// SQL connection
$insert = doInsert($firstname, $lastname);
// Execute statement using odbc_exec, etc.
}
// HTML
<input type="text" class="required" name="firstname" id="firstname" />
<input type="text" class="required" name="lastname" id="lastname" />
phpdata.php
function doInsert($firstname, $lastname) {
$insert = "INSERT INTO mytable (firstname, lastname)
VALUES ('$firstname', '$lastname')";
return $insert;
}