关于php:mysqli_num_rows()期望参数1为mysqli_result对象

mysqli_num_rows() expects parameter 1 to be mysqli_result, object

这是我第一次使用mysqli。 似乎在mysqli_num_rows()的括号之间寻找结果集的名称。 但是,当我尝试$ stmt,$ conn却一无所获时,我遇到了同样的错误。 令人沮丧! $ WHAT在下面的最后一行中会如何显示?

也许我正在尝试错误的方法。 我要做的就是检查是否返回了结果。 我真的不需要行数。 我应该只对一条错误消息执行else语句吗? 那是最好的方法吗? 是否有编写一种函数来连接和接受查询及其参数的好方法? 我为mysql写了一篇,但这是如此不同! 我不希望重写数十个查询!

1
2
3
4
5
6
7
8
9
10
11
12
13
$conn = mysqli_connect($host, $user, $pwd, $db,$port=$port_nbr);

if ($mysqli_connect_errno) {
    printf("Connect failed: %s\
"
,
    mysqli_connect_error());
    exit;
}
if($stmt=$conn->prepare("SELECT id, name, status, type FROM organization")) {
    $stmt->execute();
    $stmt->bind_result($org_id, $orgname, $orgstatus, $orgtype);    
    $num=mysqli_num_rows($WHAT);
}


当您只需要面向对象时,就将过程和面向对象的方法结合在一起。 更改

1
$num=mysqli_num_rows($WHAT);

1
$num = $stmt->num_rows();


mysqli_num_rows将查询结果作为参数
http://us.php.net/manual/en/mysqli-result.num-rows.php

您也可以以OOP样式将其用作$ result-> num_rows;。


发生此错误的原因是您可能会将$stmt对象传递给mysqli_num_rows()

而且,我看到的是您在php中混合了两种使用mysql数据库的方法-面向对象方法和过程方法。 您必须选择其中之一,然后再执行以下操作-

过程方法(使用mysqli扩展名)

1
2
3
4
5
6
$con = mysqli_connect("localhost","user","pass","test") or die("Connection Error:" . mysqli_error($conn));
$query ="SELECT id, name, status, type FROM organization";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$count = mysqli_num_rows($result);

// $count now stores the number of rows returned from that query

面向对象的方法(使用mysqli扩展名)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
$host ="localhost";
$username ="user";
$password ="pass";
$dbname ="test";

// Create connection
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed:" . $conn->connect_error);
}

$sql ="SELECT id, name, status, type FROM organization";
$result = $conn->query($sql);
$count = $result->num_rows;
// $count now stores the number of rows returned
$conn->close();
?>

您可以在这里了解更多信息-https://www.w3schools.com/php/php_mysql_select.asp