I need to implement a code in PHP which adds a new city (passed in $_POST['City']
) name in database for a given $stateID
if it does not already exist and returns its CityID generated, else use the CityID passed in $_POST['City']
. Here is the code:
$stateID = substr(filter_input(INPUT_POST, 'State'), 0, 2);
$city = filter_input(INPUT_POST, 'City', FILTER_VALIDATE_INT);
$cityID = NULL;
if(!preg_match("/[a-zA-Z]/", $city)){
$cityID = $city;
echo 'City Exists';
}
else{
# If a new city name is entered, store it in database
$params = array('ss', $stateID, $city);
$cityID = $dbh->ExecuteScalar("CALL AddNewCity(?, ?, @outCityID)", $params);
echo 'New City Added';
}
Problem is, whether the value of $city
is like ABC or like 123, the code echoes City Exists.
Please ignore the code $dbh->ExecuteScalar........
. It is using my custom built database handling library.
What is wrong with the regular expression statement?
The regex [a-zA-Z]
matches a lower or uppercase character and preg_match returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
You use filter_input with FILTER_VALIDATE_INT
.
If you enter ABC
, the value of $city
will be false and preg_match("/[a-zA-Z]/", false)
will return 0. The if statement will check for if (!0)
which will be true and you will see City Exists
If you enter 123
the value of $city
will be 123
and preg_match("/[a-zA-Z]/", 123)
will return 0. The if statement will check for if (!0)
which will be true and you will see City Exists