dsxd62219570 2018-07-20 03:24
浏览 17
已采纳

无法根据需要评估表达式匹配

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?

  • 写回答

1条回答 默认 最新

  • dream04110 2018-07-20 07:39
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值