duanke9540 2019-08-03 11:05
浏览 75
已采纳

如何使用预准备语句选择IP地址

Im trying to select an IP address using prepared statements with php, if the IP already exist its everything is ok, but if doesnt exist it does never enter inside the if($stmt -> num_rows === 0), it always enter on the elselike if the query is wrong. The field is setted to int unsigned.
So whats wrong with this prepared statement? How can make it enter in the if($stmt -> num_rows === 0) when select doesnt match anything?

$ip_long= ip2long($ip);
$stmt = $mysqli -> prepare('SELECT INET_NTOA(ip), registry_date FROM users WHERE ip = ?');
    if (
        $stmt &&
        $stmt -> bind_param('i', $ip_long) &&
        $stmt -> execute() && 
        $stmt -> store_result() &&
        $stmt -> bind_result($ip, $registry_date_checker) && 
        $stmt -> fetch()
    ) {
       if($stmt -> num_rows === 0) {
          //It does never enter here.
       }
       if($stmt -> num_rows === 1) {
          //If exist enter here.
       }
   }
   else{
       //If select not found anything it always enter here.
       echo "Error mysqli: ".$mysqli-> error; //Returns empty error
       echo "Error stmt : ".$stmt -> error; //Returns empty error
       echo "Numrows: ".$stmt -> num_rows; //Returns 0
       exit;
   }
  • 写回答

2条回答 默认 最新

  • dongpo0409 2019-08-03 12:00
    关注

    The mysqli_stmt::fetch method returns null if no rows exist in the resultset. In the boolean context null is interpreted as false.

    This means if no record is returned by your query, then your first if will go straight into the else branch.

    I would replace $stmt -> fetch() with

    ($stmt -> fetch() ?: true)
    

    in your first if. This will convert the null value into true.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度