I have a php
script that takes user input and inserts it into a MySQL database. I want to achieve a couple of things with the insert script, a) make sure only acceptable characters get captured and b) prevent SQL
injection.
I have a form element like so:
<input class="form-control" id="mrn" name="mrn" type="text" maxlength="17">
I then have in the php
script the following:
// Gather the posted data into local variables
$mrn_demographics = mysqli_real_escape_string($db_connect,preg_replace('/[^a-zA-Z0-9]/', '', $_POST['mrn']));
// Form data error handling
if($mrn_demographics == "" ){
echo "The form submission is missing data.";
} else {
// End form data error handling
$sql = "INSERT INTO nys_demographics (
mrn
)
VALUES('$mrn_demographics')";
}
Does this achieve the ability to prevent SQL
injection and is the use of the mysqli_real_escape_string
superfluous since I am also using the regex
in order to capture what I want, which is alpha-numeric characters.