I have used form data that would be passed to a PHP script that ultimately would store the data in a mySQL database. The data has always been string data. I was wondering if I had data on a form that looks like this:
Age: ( The html page and a text field )
and I have defined age in mySQL as a smallint ( -32768 to 32767 )
How do I do the conversion to make sure age is properly formatted so that it can be placed in successfully in age column in the mySQL database?
I am looking for something like:
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
I am using http://www.w3schools.com/php/php_mysql_insert.asp as a guide using the db name, table name and field names.
Assuming that you already have frontend validation:
(int)$age
if not you can use
is_numeric($age)
before you cast variable to integer
You could use php's intval() function to make sure the only thing that goes into the database is an integer. Examples;
intval("23 years") // 23
intval("23.2") // 23
intval(" 23") // 23
Please use PHP inbuilt function filter_input.
$ageOptions = array('options' =>
array('min_range' => 1, 'max_range' => 200));
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT, $ageOptions);
If the validation gets passed, value of age will be returned and FALSE if the validation fails.