-2

I create as the following function. how to get all data using this array. when run this function will appear only the first record. but, i want it to appear all the records. what is the error in this code.

public function get_All_Se($stId){
    $query = "SELECT * FROM session WHERE stId = '$stId'";
    $result = $this->db->query($query) or die($this->db->error);
    $data = $result->fetch_array(MYSQLI_ASSOC);     
return $data;
}
loke2
  • 35
  • 1
  • 8

4 Answers4

0

Run loop over all results and add to some return array.

$rows = array();

while(($row = $result->fetch_array($result))) {
    $rows[] = $row;
}
0
public function get_All_Se($stId){
             $rows=array();
    $query = "SELECT * FROM session WHERE stId = '$stId'";
    $result = $this->db->query($query) or die($this->db->error);
    while($data= $result->fetch_assoc()){
     $rows[]=$data;
    }    
              return $rows;
  }
Badshah Sahib
  • 184
  • 2
  • 11
0

As the documentation of mysqli::fetch_array() explains, it returns only one row (and not an array containing all the rows as you might think).

The function you are looking for is mysqli::fetch_all(). It returns all the rows in an array.

public function get_All_Se($stId)
{
    $query = "SELECT * FROM session WHERE stId = '$stId'";
    $result = $this->db->query($query) or die($this->db->error);
    return $result->fetch_all(MYSQLI_ASSOC);     
}

The code above still has two big issues:

  1. It is open to SQL injection. Use prepared statements to avoid it.
  2. or die() is not the proper way to handle the errors. It looks nice in a tutorial but in production code it is a sign you don't care about how your code works and, by extension, what value it provides to their users. Throw an exception, catch it and handle it (log the error, put some message on screen etc) in the main program.
Community
  • 1
  • 1
axiac
  • 68,258
  • 9
  • 99
  • 134
0

Try this way...

<?php

// run query
$query = mysql_query("SELECT * FROM <tableName>");

// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;

  // OR just echo the data:
  echo $row['<fieldName>']; // etc

}

// debug:
print_r($array); // show all array data
echo $array[0]['<fieldName>'];

?>
Hiren Makwana
  • 1,976
  • 2
  • 13
  • 28