1

I want to check if ($numRows >= 1) then it should return something.

When I use $con->mysql("{QUERY}"), it works.

But when I use $stmt = $con->prepare("{QUERY}"), it doesn't work.

Does anyone have a clue?

Working method

<?php
if ($result = $con->query("SELECT username FROM users WHERE username = 'test'")) {
    $numRows = $result->num_rows;

    echo $numRows;
}
?>

Result: 1

Not working method

<?php
$name = 'test';

$stmt = $con->prepare("SELECT username FROM users WHERE username = ?");
$stmt->bind_param('s', $name);

$name = 'test';

$stmt->execute();

$numRows = $stmt->num_rows;

echo $numRows;
?>

Result: 0

1 Answers1

5

You need to transfer the result set from the SELECT query before calling the ->num_rows() method.

// your code    

$stmt->execute();
$stmt->store_result();  
$numRows = $stmt->num_rows;

echo $numRows;

Here's the reference:

Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37