Retrieving data to HTML table from SQL database

133
September 12, 2017, at 1:35 PM

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);'.

Answer 1

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], [...],...]
}
READ ALSO
How can i get the country&#39;s ISD code from IP

How can i get the country's ISD code from IP

I need to get the countries ISD code of the site visitor based on the IP location is there any library or code that I can integrate it

90
How to read Excel file in PHP?

How to read Excel file in PHP?

I have gone through PHP-ExcelReader, But it is too old and many functions are deprecated in new PHP 7

234
Deleting a particular row using jQuery

Deleting a particular row using jQuery

I am working a web app where I am creating a invoice for the items purchasedNow in the invoice I am having to extra lines for additional charges like transportation and other services, but I can leave them blank and so they do not produce any tax

144