Robin
Robin

Reputation: 61

Alternate Way to Check Result num_rows >0

Up to now I was checking num_rows >0 the following way:

$sql = "SELECT name FROM tbl_criteria WHERE ID =?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
 header("location: /XX");
}else{
 mysqli_stmt_bind_param($stmt, "i", $cId);
 mysqli_stmt_execute($stmt);
 $result = mysqli_stmt_get_result($stmt);
 mysqli_fetch_all($result,MYSQLI_ASSOC);
 if($result-> num_rows >0{
  echo 'Appear if rows >0';
  foreach($result as $row){
   echo 'Appear for each result';
   }
  }
}

So suddenly this is not working anymore. I always get 0 results. I have read that it is important to call mysqli_stmt_store_result() before accessing num_rows otherwise it would usually return 0. I thought that I'm storing the results with $result = mysqli_stmt_get_result($stmt); or am I wrong? I am hosting my website on a webserver so it could be because of an update as well. A couple of days ago it was working fine.

Upvotes: 0

Views: 1252

Answers (1)

Dharman
Dharman

Reputation: 33238

Your code is not working most likely due to multiple syntax errors you have. I recommend to read How to get the error message in MySQLi?

If you would like to continue using mysqli, then there is no need for this overly complex code. You can simply fetch all results into an array. There's no need to ever use num_rows.

$value = "cId";
$stmt = $conn->prepare("SELECT name FROM tbl_criteria WHERE ID =?");
$stmt->bind_param('s', $value);
$stmt->execute();
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// If no rows were fetched the array will be empty and condition will be false
if ($result) {
    echo 'Appear if rows >0';
    foreach ($result as $row) {
        echo 'Appear for each result';
    }
}

Upvotes: 1

Related Questions