when I run this:
if ($result->num_rows() > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
I get the following error:
Call to undefined method mysqli_result::num_rows()
I presume the error is from the num_rows()
method but can't quite figure out what is wrong. As far as I know, objects call methods by using $obj->foo()
in OOP but when I remove the parenthesis of num_row
:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
this block of code runs as expected.
The reason the second block of code works is because num_rows
is an attribute of the object. Using num_rows()
as a method results in a undefined method error because there is no method by that name.
An example:
class Dog {
public weight;
public age;
public function __construct($weight, $age)
{
$this->weight = $weight;
$this->age = $age;
}
public function bark()
{
...
}
public function gain_weight()
{
$this->weight++;
}
}
$dog = new Dog(10, 0);
$dog->gain_weight();
echo $dog->weight;
gain_weight
is a method, but weight
is an attribute of the $dog
object.
On a side note, if ($result->num_rows > 0)
is the same as if ($result->num_rows)
since if $result->num_rows
equals 0, the statement will evaluate to false.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.