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条)

报告相同问题?