Ryan Oscar
Ryan Oscar

Reputation: 279

Retrieving data to HTML table from SQL database

I'm trying to get data to html table from database. In the database there's a company table which consists of id, name and percentage columns.

The above data in the table is entered by me manually. I need to fill those the same values by retrieving from database.

And company table in the database looks like this.Database table

In my coding it's getting an error in the place of array formation. I tried to get all the names in to one array and print in the html table. I'm kindly requesting to have a look at my coding. Highly appreciated.

$sql = "SELECT name, percentage FROM company";
$result = $conn->query($sql);

$result = $conn->query($sql);
if ($result->num_rows > 0) {

    // output data of each row
    while($row= $result->fetch_assoc()) {
      $arr=str_split($row)

       //echo  $row;
       echo "<table> <tr> <td> $arr[1] </td> </tr> </table> ";

    }
  } else {
      echo "0 results";
  }

@jakumi Error is enter image description here. Line 18 is '$arr=str_split($row);'.

Upvotes: 0

Views: 869

Answers (1)

Jakumi
Jakumi

Reputation: 8374

str_split expects a string, $row however already is an array. you access fields of each row by just $row['name'] for example.

so

echo '<table>';
while($row= $result->fetch_assoc()) {
    echo '<tr><td>'.$arr['name'].'</td><td>'.$arr['percentage'].'</td></tr>'; 
}
echo '</table>';

updated for answering a specific comment:

$percentages = [];
$namesToPercentages = [];
$collection = [];
while($row = $result->fetch_assoc()) {
    $percentages[] = $row['percentage']; 
    // this produces [0 => 0, 1=>1.1, 2=>1.2, ...]

    $namesToPercentages[$row['name']] = $row['percentage'];
    // this produces ['Base_price' => 0, 'A' => 1.1, ...]

    $collection[]= $row;
    // this produces [['name' => 'Base_price', 'percentage'=>0], [...],...]
}

Upvotes: 1

Related Questions