MySQLI Prepared Statement: num_rows & fetch_assoc

前端 未结 6 1710
我寻月下人不归
我寻月下人不归 2020-12-16 21:22

Below is some poorly written and heavily misunderstood PHP code with no error checking. To be honest, I\'m struggling a little getting my head around the maze of PHP->MySQLi

6条回答
  •  死守一世寂寞
    2020-12-16 22:00

    I searched for a long time but never found documentation needed to respond correctly, but I did my research.

    $stmt->get_result() replace $stmt->store_result() for this purpose. So, If we see

    $stmt_result = $stmt->get_result();
    var_dump($stmt_result);
    

    we get

    object(mysqli_result)[3]
      public 'current_field' => int 0
      public 'field_count' => int 10
      public 'lengths' => null
      public 'num_rows' => int 8  #That we need!
      public 'type' => int 0
    

    Therefore I propose the following generic solution. (I include the bug report I use)

    #Prepare stmt or reports errors
    ($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
    
    #Execute stmt or reports errors
    $stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
    
    #Save data or reports errors
    ($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
    
    #Check if are rows in query
    if ($stmt_result->num_rows>0) {
    
      # Save in $row_data[] all columns of query
      while($row_data = $stmt_result->fetch_assoc()) {
        # Action to do
        echo $row_data['my_db_column_name_or_ALIAS'];
      }
    
    } else {
      # No data actions
      echo 'No data here :(';
    }
    $stmt->close();
    

提交回复
热议问题