无法计数成功执行mysqli查询

时间:2017-05-21 15:48:01

标签: php mysqli insert-into

我想知道我的查询是否成功(好吧,我成功地执行了插入查询)但是在第25行得到了这个错误:“mysqli_num_rows()期望参数1是mysqli_result,布尔给出”我已经检查每一行,我甚至使用mysqli_affected_rows并失败。感谢任何帮助,这是我的代码:

<?php
   include "connection.php";  
   $fn = $_POST['first_name'];
   $ln = $_POST['last_name'];
   $uname = $_POST['username'];
   $pwd = $_POST['password'];
   $stat = $_POST['status'];  
   if($fn=="" || $ln=="" || $uname=="" || $pwd=="" || $stat==""){
     echo "ALL FIELD MUST BE FILLED!";
   }                                                                        
   else {
     $sql = "SELECT * from user WHERE username='$uname'";
     $result = mysqli_query($conn, $sql);
     $number = mysqli_num_rows($result);
   if ($number != 0) {
     echo "Username $uname is not available";
   }
   else {
     $options = ['cost' => 12];
     $pwd = password_hash($pwd, PASSWORD_BCRYPT, $options);
     $query = "INSERT INTO user 
              (username,password,first_name,last_name,status) VALUES 
              ('$uname','$pwd','$fn','$ln','$stat')";
     $res = mysqli_query($conn, $query);
     $nmb = mysqli_num_rows($res);

     echo $nmb;                                                             
    }                                                                         
  }                                                                         
?>                                                                                  

2 个答案:

答案 0 :(得分:1)

$nmb = mysqli_num_rows($res);无效,因为$res是INSERT查询的结果。 The documentation for mysqli_query说:

  

失败时返回FALSE。对于成功的SELECT,SHOW,DESCRIBE或EXPLAIN查询,mysqli_query()将返回一个mysqli_result对象。对于其他成功的查询,mysqli_query()将返回TRUE。

因此,$res始终为falsetrue,您将无法使用mysqli_num_rows()mysqli_affected_rows()。问题是,无论如何,计算行数确实没有意义。您正在尝试插入一条记录,因此它要么是一条或零,所以真或假的结果应该足以让您检测查询是否成功。

答案 1 :(得分:-1)

改变这个:

$res = mysqli_query($conn, $query);

$nmb = mysqli_num_rows($res);

echo $nmb; 

为此:

$res = mysqli_query($conn, $query);
if ($res) { 
   echo "Insert ok";
}
else
{
   echo "Problem to insert";
}