mysqli query only returning first row

前端 未结 5 2067
不思量自难忘°
不思量自难忘° 2020-12-12 03:16

I am migrating from mysql to mysqli, and I am having trouble returning more than one row from the database in a query.

$db = new mysqli($hostname, $sql_us, $         


        
相关标签:
5条回答
  • 2020-12-12 03:22

    You need to store while loop values into array try this

    $rows = array();
    if ($type == 'assoc') {
        while($row = $result->fetch_assoc()) {
          $rows[] = $row;
        }
    } else {    
        while($row = $result->fetch_object()) {
          $rows[] = $row;
        }   
    }
    return $rows;
    
    0 讨论(0)
  • 2020-12-12 03:24
    $arr = array();
    if ($type == 'assoc') {
      while($row = $result->fetch_assoc()) {
        $arr[] = $row;
      }
    }
    else {    
      while($row = $result->fetch_object()) {
        $arr[] = $row;   
      }
    }
    return $arr;
    
    0 讨论(0)
  • 2020-12-12 03:37

    You are only returning the first row. You have to return an array.

    0 讨论(0)
  • 2020-12-12 03:41

    When you return in a function it stops executing at that point and goes back to the where it was called from with the value that you are returning.

    In your case when you do a return $row, you are getting out of the function as soon as the first row is read.

    Fix is:

    $result = array();
    if ($type == 'assoc') {
        while($row = $result->fetch_assoc()) {
          $result[] = $row;
        }
    
    } else {    
    
        while($row = $result->fetch_object()) {
          $result[] = $row;
        }   
    }
    return $row;
    
    0 讨论(0)
  • 2020-12-12 03:47

    Use this code:

    $rows = array();
    if ($type == 'assoc') {
        while($row = $result->fetch_assoc()) {
          $rows[] = $row;
        }
    } else {    
        while($row = $result->fetch_object()) {
          $rows[] = $row;
        }   
    }
    return $rows;
    

    You are using the return inside the while and return terminates the while loop after first iteration that's why you are getting only one row.

    0 讨论(0)
提交回复
热议问题